What's do list comprehensions do that generator expressions don't?

Robert Kern rkern at ucsd.edu
Mon Apr 25 07:27:18 EDT 2005


jfj wrote:
> Robert Kern wrote:
> 
>> jfj wrote:
>>
>>> 2) to convert a list/tuple/string to a list, which is
>>> done extremely fast.
>>
>> Add "any iteratable". Genexps are iterables.
> 
> The thing is that when you want to convert a tuple to a list
> you know already the size of it and you can avoid using append()
> and expanding the list gradually.  For iterables you can't avoid
> appending items until StopIteration so using list() doesn't have
> any advantage.

But no real disadvantage either.

> The OP was about genexps vs list comprehensions
> but this is about list() vs. list comprehensions.

Yes, and list(genexp) replaces list comprehensions rather handily. 
There's very little reason to prefer list comprehensions over the 
list(genexp) construction. If anything, it's pretty much a wash. That 
was the OP's question:

[mike]
 > when would I use a list comp instead of a generator expression if
 > I'm going to require 2.4 anyway?

>> Possibly. I find them too similar with little enough to choose between 
>> them, hence the OP's question. 
> 
> One solution is to forget about list().  If you want a list use []. 
> Unless you want to convert a tuple...
> 
> I think a better question would be "What do *generator expressions* do
> that list comprehensions don't?".  And always use list comprehensions
> unless you want the extra bit.

<shrug> What we have now are two very similar constructs, one of which 
is more general and subsumes nearly all the uses of the other. The 
presence of both is confusing, as evidenced by the fact that the OP 
asked his question. In the Great Breaking of Backwards Compatibility, 
list comprehensions should go away.

-- 
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