Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

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

0 views
Skip to first unread message

Mark English

unread,
Apr 25, 2005, 10:44:41 AM4/25/05
to pytho...@python.org
> Date: Mon, 25 Apr 2005 08:51:17 -0500
> From: Mike Meyer <m...@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).

Mark

-----------------------------------------------------------------------
The information contained in this e-mail is confidential and solely
for the intended addressee(s). Unauthorised reproduction, disclosure,
modification, and/or distribution of this email may be unlawful. If you
have received this email in error, please notify the sender immediately
and delete it from your system. The views expressed in this message
do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies.
-----------------------------------------------------------------------

Robert Kern

unread,
Apr 25, 2005, 10:56:55 AM4/25/05
to pytho...@python.org

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
rk...@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

0 new messages