if does not evaluate

Peter Otten __peter__ at web.de
Fri Jun 11 11:19:56 EDT 2004


Jim Newton wrote:

> sorry, i do not understand.  The python syntax is a bit
> difficult for me.

Maybe I obscured the issue by comparing name attributes to a string instead
of using a predicate() function.

> if i have a list x and a function f how do i know if
> there is an element of x on which f returns something
> other than False?

Using the above identifiers, let's assume we are looking for a name starting
with "M":

>>> x = ["Peter", "Paul", "Mary", "Jane"]
>>> def f(o):
...     print "checking", o
...     return o.startswith("M")
...

If we call

>>> map(f, x)
checking Peter
checking Paul
checking Mary
checking Jane
[False, False, True, False]

it invokes f() for every item in x and returns the above list of booleans.
The equivalent list comprehension would be [f(i) for i in x]. Now

>>> True in map(f, x)
checking Peter
checking Paul
checking Mary
checking Jane
True

gives the correct result but unfortunately does too much work as we don't
need to calculate f("Jane") when we already know the outcome. Enter
generator

>>> def lazymap(predicate, seq):
...     for item in seq:
...             yield predicate(item)
...

which calulates f(item) as needed. Proof:

>>> True in lazymap(f, x)
checking Peter
checking Paul
checking Mary
True
>>>

itertools.imap() is just the fast C implementation of lazymap().
The equivalent generator expression (new in Python 2.4) will be 
(f(i) for i in x).

Peter




More information about the Python-list mailing list