Generator expressions v/s list comprehensions

Christophe Cavalaria chris.cavalaria at free.fr
Sat Aug 28 16:44:28 EDT 2004


Mahesh Padmanabhan wrote:

> In article <1gj8y77.6qshr41q531veN%aleaxit at yahoo.com>,
>  aleaxit at yahoo.com (Alex Martelli) wrote:
> 
> 
>> Sure, and that limitation is: list comprehensions return lists.  This
>> one "limitation" (together with Python's applicative order evaluation,
>> and you couldn't change THAT without breaking the whole caboodle of
>> existing programs!) implies everything else.
> 
> Is returning a list really a limitation considering that lists can be
> transformed quite easily?
> 
> What is "Python's applicative order evaluation" and how do generator
> expressions get around it?
> 
> 
>> Generator comprehensions are wonderful and there is no way Python list
>> comprehensions can provide the same features, since lists need to be
>> lists.  Sure, list(e(x) for x in foo) IS just the same thing as [e(x)
>> for x in foo].  We'll remove the redundancy in 3.0 -- not earlier
>> because it will break backwards compatibility.  The only sensible way I
>> can see right now for 3.0 to remove this redundancy is by removing list
>> comprehensions and leaving only generator comprehensions, btw.
> 
> I am still not clear of the advantages of using generator expressions
> (other than less memory consumption) instead of list comprehension for
> any given class of problems. Can you cite concrete use cases where
> generator expressions would be preferred over list comprehension?
> 
> Thanks,
> Mahesh

- lower memory usage
- lower CPU usage ( sometimes, you don't need to expand the whole generator,
see below )
- ability to manipulate infinite generators

Is that enouth ? 



More information about the Python-list mailing list