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

Robert Kern rkern at ucsd.edu
Mon Apr 25 10:56:55 EDT 2005


Mark English wrote:
>>Date: Mon, 25 Apr 2005 08:51:17 -0500
>>From: Mike Meyer <mwm at mired.org>
> 
> 
>>Which means that the real rule should be always use generator
> 
> expressions,
> 
>>unless you *know* the expression will always fit in memory.
> 
> 
>>Which leads to the obvious question of why the exception.
> 
> <code>
> 
>>>>l = [(1, 2), ('a', 'b'), (3, 2), (23, 32)]
>>>>l
> 
> [(1, 2), ('a', 'b'), (3, 2), (23, 32)]
> </code>
> This screen dump of the object is quite useful to me.
> 
> <code>
> 
>>>>r = reversed(l)
>>>>r
> 
> <listreverseiterator object at 0x009D2B90>
> </code>
> This screen dump of the object is less useful to me.
> 
>>From a pure programming point of view it's not a sufficient reason to
> keep list comprehensions, especially as the interpreter shell could be
> massaged into giving more output, but right here right now it's a lot
> easier to read the former than the latter IMHO.
> 
> (That is assuming I'm right in assuming functions like "reversed" are
> generator expressions).

No, generator expressions are like list comprehensions, only they create 
generator objects.

(x*x for x in xrange(1000))

versus

[x*x for x in xrange(1000))

Of course, one can always get an explicit list by passing the generator 
  object to list(). This also works for most iterables like the one you 
showed above.

list(x*x for x in xrange(1000))

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