newbie q
Bengt Richter
bokr at oz.net
Thu Jan 13 19:08:09 EST 2005
On Thu, 13 Jan 2005 09:16:40 -0500, Steve Holden <steve at holdenweb.com> 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):
>>> 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.
Regards,
Bengt Richter
More information about the Python-list
mailing list