[Python-checkins] r46988 - sandbox/trunk/Doc/functional.rst
andrew.kuchling
python-checkins at python.org
Fri Jun 16 02:44:02 CEST 2006
Author: andrew.kuchling
Date: Fri Jun 16 02:44:02 2006
New Revision: 46988
Modified:
sandbox/trunk/Doc/functional.rst
Log:
Mention generator expressions
Minor typographical fix
Add notes for reference section
Modified: sandbox/trunk/Doc/functional.rst
==============================================================================
--- sandbox/trunk/Doc/functional.rst (original)
+++ sandbox/trunk/Doc/functional.rst Fri Jun 16 02:44:02 2006
@@ -338,8 +338,11 @@
Note that in all case the resulting ``stripped_list`` is a Python list
containing the resulting lines, not an iterator. This means that list
-comprehensions aren't very useful if you're working with iterators
-that return an infinite or a very large stream of data.
+comprehensions aren't very useful if you're working with iterators
+that return an infinite or a very large stream of data. Later we'll
+discuss generator expressions, a feature that provides similar
+capabilities as list comprehensions but can be used with infinite
+iterators.
List comprehensions have the form::
@@ -396,6 +399,28 @@
[ (x,y) for x in seq1 for y in seq2]
+Generator Expressions
+-----------------------
+
+Generator expressions are written like list comprehensions, but are
+surrounded by parentheses (\samp{()}) and not square brackets
+(\samp{[]}). The result of a generator expression
+is an iterator that returns the computed elements without
+materializing a list containing them all.
+
+::
+
+ (line.strip() for line in line_list) =>
+ 'line 1', 'line 2'
+
+Generator expressions always have to be written inside parentheses, as
+in the above example. The parentheses signalling a function call also
+count, so if you want to create an iterator that will be immediately
+passed to a function you could write::
+
+ obj_total = sum(obj.count for obj in list_all_objects())
+
+
Generators
-----------------------
@@ -691,7 +716,7 @@
::
enumerate(['subject', 'verb', 'object']) =>
- [(0, 'subject'), (1, 'verb'), (2, 'object')]
+ (0, 'subject'), (1, 'verb'), (2, 'object')
``enumerate()`` is often used when looping through a list
and recording the indexes at which certain conditions are met::
@@ -1118,3 +1143,14 @@
sys.stdout.write(str(elem))
sys.stdout.write(', ')
print elem[-1]
+
+
+References
+--------------------
+
+SICP
+
+Relevant manual sections
+
+XXX
+
More information about the Python-checkins
mailing list