for_some(),for_all()?

Steven Bethard steven.bethard at gmail.com
Thu Sep 23 11:12:00 EDT 2004


Raymond Hettinger <vze4rx4y <at> verizon.net> writes:
> For pure speed, the following is faster and gives short-circuit behavior:
> 
> >>> from itertools import ifilter
> >>> def any(seq, pred=None):
> ...     for elem in ifilter(pred, seq):
> ...         return True
> ...     return False

So, the other one also has short-circuit behavior:

>>> def any(seq, pred=bool):
...     return True in imap(pred, seq)
...
>>> def pred(x):
...     return x > 3
...
>>> i = iter(range(10))
>>> any(i, pred)
True
>>> list(i)
[5, 6, 7, 8, 9]

Could you explain what makes the second one faster?  I'm guessing it's 
something like that comparing True to each element in the iterable costs more 
than binding each element in the iterable to elem...?

Thanks,

STeve




More information about the Python-list mailing list