views:

97

answers:

4

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.

+6  A: 

Use the built-in any function.

e.g.

any(<condition> for it in <iterable>)      # return True on <condition>
KennyTM
@Yuval: [No you don't](http://www.python.org/dev/peps/pep-0289/).
KennyTM
+1 because it's the only correct solution. Period. Why misuse list comprehensions when there's any and generator expressions?
delnan
A: 

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)
Yuval A
You should leave those square brackets out. any/all work fine (better even since it short circuits) with generator expressions
gnibbler
@gnibbler - true, thanks.
Yuval A
@Yuval A: Why do you write `any(True for x in it if x ==2)` instead of `any(x == 2 for x in it)`?
John Machin
@John - just another option, using list complrehensions
Yuval A
@Yuval A: I was asking you to compare a baroque expression with a minimal expression, irrespective of whether it was in a list comprehension (yuk) or a generator expression.
John Machin
A: 

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)
Nikolaus Gradwohl
there's a function called 'all' ...
Will
+1  A: 

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>)
Dave Kirby