diff options
author | Raymond Hettinger <python@rcn.com> | 2004-05-19 19:45:19 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2004-05-19 19:45:19 (GMT) |
commit | 170a62221cfdff24b52cba5fc71e59342f3b4c61 (patch) | |
tree | a4fc9020007e79324343907c201409229552fd43 /Doc/tut | |
parent | ba91b9fdda5e3ecc4af447a53ee11789eca9e16b (diff) | |
download | cpython-170a62221cfdff24b52cba5fc71e59342f3b4c61.zip cpython-170a62221cfdff24b52cba5fc71e59342f3b4c61.tar.gz cpython-170a62221cfdff24b52cba5fc71e59342f3b4c61.tar.bz2 |
Add more docs for generator expressions.
* Put in a brief, example driven tutorial entry.
* Use better examples in whatsnew24.tex.
Diffstat (limited to 'Doc/tut')
-rw-r--r-- | Doc/tut/tut.tex | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/Doc/tut/tut.tex b/Doc/tut/tut.tex index 87bc424..c8c5afe 100644 --- a/Doc/tut/tut.tex +++ b/Doc/tut/tut.tex @@ -4399,6 +4399,39 @@ generators terminate, they automatically raise \exception{StopIteration}. In combination, these features make it easy to create iterators with no more effort than writing a regular function. +\section{Generator Expressions\label{genexps}} + +Some simple generators can be coded succinctly as expressions using a syntax +like list comprehensions but with parentheses instead of brackets. These +expressions are designed for situations where the generator is used right +away by an enclosing function. Generator expressions are more compact but +less versatile than full generator definitions and the tend to be more memory +friendly than equivalent list comprehensions. + +Examples: + +\begin{verbatim} +>>> sum(i*i for i in range(10)) # sum of squares +285 + +>>> xvec = [10, 20, 30] +>>> yvec = [7, 5, 3] +>>> sum(x*y for x,y in zip(xvec, yvec)) # dot product +260 + +>>> from math import pi, sin +>>> sine_table = dict((x, sin(x*pi/180)) for x in range(0, 91)) + +>>> unique_words = set(word for line in page for word in line.split()) + +>>> valedictorian = max((student.gpa, student.name) for student in graduates) + +>>> data = 'golf' +>>> list(data[i] for i in range(len(data)-1,-1,-1)) +['f', 'l', 'o', 'g'] + +\end{verbatim} + \chapter{Brief Tour of the Standard Library \label{briefTour}} |