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@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

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to