list and generators (WAS: counting items)

Steven Bethard steven.bethard at gmail.com
Wed Jan 12 17:35:31 EST 2005


Michael Hartl wrote:
> That's cool!  Of course, walk returns a generator, so using a list
> comprehension to turn it into a list seems natural, but I didn't
> realize that list() does the same thing (and neither, apparently, did
> the original implementor) -- although, with a little reflection, it
> obviously must!

Yup.  Also worth noting is that if you want the scoping rules of 
generator expression, but need a list instead, you can just call list 
with the generator expression:

py> x
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
NameError: name 'x' is not defined
py> [pow(x, 7, 23) for x in range(10)]
[0, 1, 13, 2, 8, 17, 3, 5, 12, 4]
py> x
9
py> del x
py> x
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
NameError: name 'x' is not defined
py> list(pow(x, 7, 23) for x in xrange(10))
[0, 1, 13, 2, 8, 17, 3, 5, 12, 4]
py> x
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
NameError: name 'x' is not defined

Note that with the generator expression, 'x' doesn't get leaked to the 
enclosing scope.

Steve



More information about the Python-list mailing list