[Tutor] lambdas, generators, and the like

spir denis.spir at gmail.com
Thu Jan 16 11:31:10 CET 2014


On 01/12/2014 07:40 PM, Keith Winston wrote:
> Thanks Dave, that looks like a good idea, I've played a little with
> one-line generators (? the things similar to list comprehensions), but
> I'm still wrapping my head around how to use them.

You probably mean a generator *expression*. it's written like a list 
comprehension, bit with () instead of []. The semantic difference is that items 
are generated once at a time instead of all in one go and stored in a list. 
Another difference is that one cannot reuse such a generator object (once end is 
reached, it is like "empty").

spir at ospir:~$ python3
Python 3.3.1 (default, Sep 25 2013, 19:29:01)
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1,2,3]
>>> squares = [n*n for n in l]
>>> squares
[1, 4, 9]
>>> for (i,sq) in enumerate(squares):
...     print(i+1, sq)
...
1 1
2 4
3 9
>>> squares = (n*n for n in l)
>>> squares
<generator object <genexpr> at 0x7f92496a7be0>
>>> for (i,sq) in enumerate(squares):
...     print(i+1, sq)
...
1 1
2 4
3 9
>>>


More information about the Tutor mailing list