Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Python equivalent of Ruby's 'any?' function?

Tags:

python

list

ruby

In Ruby, you can call Enumerable#any? on a enumerable object to see if any of its elements satisfies the predicate you pass in the block. Like so:

lst.any?{|e| pred(e) }

In Python, there's an any function that does something similar, but on a list of booleans.

Of course, for a reasonably-sized list, I'd just do:

any(map(pred,lst))

However, if my list is very long, I don't want to have to do the entire map operation first.

So, the question: Is there a generic short-circuiting any function in Python?

Yes, I know it's really trivial to write one myself, but I'd like to use speedy builtin functions (and also not reinvent any wheels).

like image 686
perimosocordiae Avatar asked Feb 24 '10 01:02

perimosocordiae


1 Answers

any(pred(x) for x in lst)

alternatively

from itertools import imap
any(imap(pred, lst))
like image 119
John La Rooy Avatar answered Sep 19 '22 05:09

John La Rooy