what is it, that I don't understand about python and lazy evaluation?
MRAB
python at mrabarnett.plus.com
Thu Aug 13 07:23:50 EDT 2009
Erik Bernoth wrote:
> Hi List,
>
> look at the following code:
>
> def evens():
> # iterator returning even numbers
> i = 0
> while True:
> yield i
> i += 2
>
> # now get all the even numbers up to 15
> L = [n for n in evens() if n < 15]
>
> Isn't it strange, that this code runs (in a lazy language) for eternity?
> I would expect python to to spit out (in no time):
> >> L
> [0, 2, 4, 6, 8, 10, 12, 14]
>
> after 14 it is not nessesary to evaluate evens() any further.
>
It's equivalent to:
L = []
for n in evens():
if n < 15
L.append(n)
More information about the Python-list
mailing list