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

jfj jfj at freemail.gr
Mon Apr 25 05:59:34 EDT 2005


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.  The OP was about genexps vs list comprehensions
but this is about list() vs. list comprehensions.

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


jfj




More information about the Python-list mailing list