What's do list comprehensions do that generator expressions don't?
Bengt Richter
bokr at oz.net
Tue Apr 26 02:36:43 EDT 2005
On Mon, 25 Apr 2005 16:48:46 -0400, Bill Mill <bill.mill at gmail.com> wrote:
>On 25 Apr 2005 23:33:48 +0300, Ville Vainio <ville at spammers.com> wrote:
>> >>>>> "Jeremy" =3D=3D Jeremy Bowers <jerf at jerf.org> writes:
>>=20
>> Jeremy> On Sun, 24 Apr 2005 22:59:12 -0700, Robert Kern wrote:
>> >> Never. If you really need a list
>> >>
>> >> list(x*x for x in xrange(10))
>> >>
>> >> Sadly, we can't remove list comprehensions until 3.0.
>>=20
>> Jeremy> Why "remove" them? Instead, we have these things called
>> Jeremy> "comprehensions" (which, now that I say that, seems a
>> Jeremy> rather odd name), and you can control whether they result
>> Jeremy> in a list or a generator with () or [].
>>=20
>> Still, list comprehensions should be implemented in terms of genexps
>> to get rid of the LC variable that is visible outside the scope of the
>> LC.
>>=20
>
>+1 . I think that we should still have the form [genexp] , but without
>the dangling variable, and implemented with generator expressions. It
>seems to me that it is inconsistent if I can do list(genexp) but not
>[genexp] , since they are so similar. Once that happens, we can tell
>people who ask the OP's question that [genexp] is just another way to
>spell list(genexp), and he should use it if he wants the entire list
>constructed in memory.
ISTM you have to account for
>>> def foo(g): return g
...
>>> foo(123)
123
>>> foo(c for c in 'abc')
<generator object at 0x02EF154C>
>>> [(c for c in 'abc')]
[<generator object at 0x02EF158C>]
>>> [c for c in 'abc']
['a', 'b', 'c']
>
>> Jeremy> should be relatively simple), it's not worth breaking that
>> Jeremy> code.
>>=20
>> Well, the code that relies on the dangling variable deserves to break.
>
>Agreed.
>
Probably ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list