Bengt Richter wrote:
On Thu, 13 Jan 2005 09:16:40 -0500, Steve Holden <[EMAIL PROTECTED]> wrote:
[...]
Any statement of the form
for i in [x for x in something]:
can be rewritten as
for i in something:
Note that this doesn't mean you never want to iterate over a list
comprehension. It's the easiest way, for example, to iterate over the
first item of each list in a list of lists:
for i in [x[0] for x in something]:
As I'm sure you know, with 2.4's generator expressions you
don't have to build the temporary list.
Which could be important if 'something'
is (or generates) a huge sequence.
for i in (x[0] for x in something):
Yes. While I haven't yet done any more than play with generator
sequences I do really feel that more of "the best of Icon" has arrived
in Python with this new addition.
>>> something = ([x] for x in xrange(10,20))
>>> something
<generator object at 0x02EF176C>
>>> list(something)
[[10], [11], [12], [13], [14], [15], [16], [17], [18], [19]]
>>> for i in (x[0] for x in something): print i,
...
oops, that list() used it up ;-)
>>> something = [[x] for x in xrange(10,20)]
>>> for i in (x[0] for x in something): print i,
...
10 11 12 13 14 15 16 17 18 19
Really nice.
I quite agree. It's particularly useful for infinite sequences :-)
regards
Steve
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list