What's do list comprehensions do that generator expressions don't?
Robert Kern
rkern at ucsd.edu
Mon Apr 25 16:26:19 EDT 2005
Jeremy Bowers wrote:
> 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.
>
>
> Why "remove" them? Instead, we have these things called "comprehensions"
> (which, now that I say that, seems a rather odd name), and you can control
> whether they result in a list or a generator with () or [].
They are *not* the same thing. They have completely different
implementations although they have very similar syntax and the former
subsumes just about *every* use of the latter. That's pointless except
for maintaining backwards compatibility. The difference in
implementation is one reason why generator expressions were not called
generator comprehensions.
What's more, the list comprehension implementation is warty. It leaks
variables.
> I don't see why they need to be "removed". Lists are already a special
> case of the "only one way to do it" principle ([] vs. list()), and
> pragmatically I don't see any reason to remove them here; it doesn't add
> comprehensibility,
Yes it does. The OP was confused as to which to use now that both exist.
This has come up here before.
> leaving them in doesn't significantly affect the mental
> size of the code (the *comprehension* is the hard part, the final form
> should be relatively simple), it's not worth breaking that code.
Like I said, this would only happen at 3.0 when all of your code will
break anyways.
--
Robert Kern
rkern at ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
More information about the Python-list
mailing list