Passing a list of conditions to a function to be checked

Viewed 182

I have an list of n conditions, for example

cond = [x > 0, x < 10, x == 2]

where x is any variable I wish to test against those conditions. I can easily test these conditions if x is already defined, but what if I want to pass this set of conditions to another function where x has not already been defined? Is there a way in Python to pass this set of conditions while keeping x an anonymous variable? If not, is there an alternative?

1 Answers

You're probably looking for an anonymous function or lambda

This could be

cond = [
    lambda x: x > 0,
    lambda x: x < 10,
    lambda x: x == 2,
]
>>> [f(5) for f in cond]
[True, True, False]

or as @John Coleman suggests in a comment you could have them all together

cond = lambda x: all((x > 0, x < 10, x == 2))  # tuple of booleans
>>> cond(5)
False
>>> cond(2)
True

If it's the same as the example, you could check the last case == 2

Related