on Generators vs. List Comprehensions

Top Page

Reply to this message
Author: Andy Sy
To: python
Subject: on Generators vs. List Comprehensions
I love list comprehensions and took to them like a duck to
water, however, I have difficulty appreciating generators
to this day.

It's interesting however how generators are supposed to be
analogous to list comprehensions in roughly the same way
xrange() is to range().

I certainly found the posts here


very illuminating and will be revisiting generators armed
with a new perspecttive.

Another possible benefit of generators - PERFORMANCE - accdg.
to David Mertz in http://www-106.ibm.com/developerworks/library/l-pygen.html

"In Python, function invocation is rather expensive; among other
factors, function arguments lists take a while to sort out (positional
and default arguments need to be parsed, among other things). Also,
initializing a frame object takes some setup steps (over 100 lines
of C, according to Tim Peters on comp.lang.python; I have not examined
the Python source myself). Resuming a generator, in contrast, is
quite cheap; the arguments have already been parsed, and the frame
object is just sitting around waiting for resumption (almost no extra
initialization is needed)."


reply to: a n d y @ n e t f x p h . c o m

Philippine Pythonista Hangout
python@??? (#Python @ irc.free.net.ph)
Searchable Archives: http://marc.free.net.ph