Reputation: 8333
I have lots of small pieces of code that look like:
for it in <iterable>:
if <condition>:
return True/False
Is there a way I can rewrite this piece of code with a lambda expression ? I know I can factor it out in a small method/function, but I am looking for some lambda thing if it can be done.
Upvotes: 2
Views: 237
Reputation: 26552
In addition to what everyone else has said, for the reverse case:
for it in <iterable>:
if <condition>:
return False
return True
use all():
b = all(<condition> for it in <iterable>)
Upvotes: 1
Reputation: 165212
Here is a simple example which returns True
if any of the objects in it
is equal to 2
. by using the map
function:
any(map(lambda x: x==2, it))
Change the lambda expression to reflect your condition.
Another nice way is to use any
with a list comprehension:
any([True for x in it if x==2])
or alternatively, a generator expression:
any(x==2 for x in it)
Upvotes: 0
Reputation: 20124
if you want to check the condition for every item of iterable you can use listcomprehensions to to this
b = [ x == whatever for x in a ]
you can combine this with any if you only need to know if there is one element that evals to true for your condition
b = any(x == whatever for x in a)
Upvotes: 0
Reputation: 523214
Use the built-in any
function.
e.g.
any(<condition> for it in <iterable>) # return True on <condition>
Upvotes: 6