Lambda the Ultimate

inactiveTopic Scope, generators and list comprehensions (Python)
started 2/5/2004; 8:27:18 AM - last post 2/7/2004; 6:53:44 AM
Ehud Lamm - Scope, generators and list comprehensions (Python)  blueArrow
2/5/2004; 8:27:18 AM (reads: 8506, responses: 4)
Scope, generators and list comprehensions (Python)
The standard scoping rules are inconvenient for the lazy evaluation of generator expressions, but it's very strange for a list comprehension and an apparently identical generator expression to produce different results.

Try to guess the output from these expressions:

>>> lst = [lambda x:x+y for y in range(3)]
>>> for f in lst:print f(0)
???

>>> gen = (lambda x:x+y for y in range(3)) >>> for f in gen:print f(0) ???

I just love this sort of thing. Maybe this should go in the fun department...

P.S

The URL given at the Daily Python-URL is wrong.


Posted to Python by Ehud Lamm on 2/5/04; 8:36:13 AM

Tom Duff - Re: Scope, generators and list comprehensions (Python)  blueArrow
2/5/2004; 9:10:11 AM (reads: 566, responses: 2)
Hmm. I don't do python, so I pasted the lines into the python interpreter and got the following:
% python
Python 1.5.2 (#1, Jan 31 2003, 14:50:26)  [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> lst = [lambda x:x+y for y in range(3)]
  File "<stdin>", line 1
    lst = [lambda x:x+y for y in range(3)]
                          ^
SyntaxError: invalid syntax
(Added later) Ah! I see we're running an ancient version of Python. Never mind.

Ehud Lamm - Re: Scope, generators and list comprehensions (Python)  blueArrow
2/5/2004; 9:34:56 AM (reads: 561, responses: 0)
One of the nice things about Python (from a strictly LtU perspective, of course) is that the language is constantly evolving...

scruzia - Re: Scope, generators and list comprehensions (Python)  blueArrow
2/5/2004; 10:27:42 AM (reads: 546, responses: 0)
... an ancient version of Python ...

Generator expressions are a very new feature, not yet implemented in any packaged Python release. According to PEP 289, the plan is for them to go into 2.4 (the current release is 2.3.3).

There's another discussion of this issue on the Python developers' mailing list:

http://mail.python.org/pipermail/python-dev/2004-January/thread.html#41951

Ehud Lamm - Re: Scope, generators and list comprehensions (Python)  blueArrow
2/7/2004; 6:53:44 AM (reads: 271, responses: 0)
Matthias, as always, clearly explains were the bodies are buried.