Dangerous behavior of list(generator)

Benjamin Kaplan benjamin.kaplan at case.edu
Sat Dec 12 21:16:36 EST 2009


On Sat, Dec 12, 2009 at 9:01 PM, Ned Deily <nad at acm.org> wrote:
> In article
> <ec96e1390912121653w56c3dbe3p859a7b979026bf47 at mail.gmail.com>,
>  Benjamin Kaplan <benjamin.kaplan at case.edu> wrote:
>> On Sat, Dec 12, 2009 at 7:15 PM, Tom Machinski <tom.machinski at gmail.com>
>> wrote:
>> > In most cases, `list(generator)` works as expected. Thus,
>> > `list(<generator expression>)` is generally equivalent to `[<generator
>> > expression>]`.
>> Actually, it's list(generator) vs. a list comprehension. I agree that
>> it can be confusing, but Python considers them to be two different
>> constructs.
>>
>> >>> list(xrange(10))
>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>> >>> [xrange(10)]
>> [xrange(10)]
>
> That's not a list comprehension, that's a list with one element.
>
>>>> [x for x in xrange(10)]
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>
> <CrocodileDundee> Now *that's* a list comprehension. </CrocodileDundee>
>

I know. But the OP was wondering why list(<generator expression>) was
behaving differently than [<generator-expression>] and I was pointing
out that list comprehensions are considered their own syntax- the list
comprehension [x for x in xrange(10)] is different than [(x for x in
xrange(10)].
> --
>  Ned Deily,
>  nad at acm.org
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list