korsygfhrtzangaiide
Elepffwdsff
/
usr
/
share
/
doc
/
python-docs-2.7.5
/
html
/
howto
/
Upload FileeE
HOME
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Functional Programming HOWTO — Python 2.7.5 documentation</title> <link rel="stylesheet" href="../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '2.7.5', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 2.7.5 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="top" title="Python 2.7.5 documentation" href="../index.html" /> <link rel="up" title="Python HOWTOs" href="index.html" /> <link rel="next" title="Logging HOWTO" href="logging.html" /> <link rel="prev" title="Idioms and Anti-Idioms in Python" href="doanddont.html" /> <link rel="shortcut icon" type="image/png" href="../_static/py.png" /> <script type="text/javascript" src="../_static/copybutton.js"></script> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="logging.html" title="Logging HOWTO" accesskey="N">next</a> |</li> <li class="right" > <a href="doanddont.html" title="Idioms and Anti-Idioms in Python" accesskey="P">previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="http://www.python.org/">Python</a> »</li> <li> <a href="../index.html">Python 2.7.5 documentation</a> » </li> <li><a href="index.html" accesskey="U">Python HOWTOs</a> »</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="functional-programming-howto"> <h1>Functional Programming HOWTO<a class="headerlink" href="#functional-programming-howto" title="Permalink to this headline">¶</a></h1> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">A. M. Kuchling</td> </tr> <tr class="field-even field"><th class="field-name">Release:</th><td class="field-body">0.31</td> </tr> </tbody> </table> <p>In this document, we’ll take a tour of Python’s features suitable for implementing programs in a functional style. After an introduction to the concepts of functional programming, we’ll look at language features such as <a class="reference internal" href="../glossary.html#term-iterator"><em class="xref std std-term">iterator</em></a>s and <a class="reference internal" href="../glossary.html#term-generator"><em class="xref std std-term">generator</em></a>s and relevant library modules such as <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><tt class="xref py py-mod docutils literal"><span class="pre">itertools</span></tt></a> and <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><tt class="xref py py-mod docutils literal"><span class="pre">functools</span></tt></a>.</p> <div class="section" id="introduction"> <h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2> <p>This section explains the basic concept of functional programming; if you’re just interested in learning about Python language features, skip to the next section.</p> <p>Programming languages support decomposing problems in several different ways:</p> <ul class="simple"> <li>Most programming languages are <strong>procedural</strong>: programs are lists of instructions that tell the computer what to do with the program’s input. C, Pascal, and even Unix shells are procedural languages.</li> <li>In <strong>declarative</strong> languages, you write a specification that describes the problem to be solved, and the language implementation figures out how to perform the computation efficiently. SQL is the declarative language you’re most likely to be familiar with; a SQL query describes the data set you want to retrieve, and the SQL engine decides whether to scan tables or use indexes, which subclauses should be performed first, etc.</li> <li><strong>Object-oriented</strong> programs manipulate collections of objects. Objects have internal state and support methods that query or modify this internal state in some way. Smalltalk and Java are object-oriented languages. C++ and Python are languages that support object-oriented programming, but don’t force the use of object-oriented features.</li> <li><strong>Functional</strong> programming decomposes a problem into a set of functions. Ideally, functions only take inputs and produce outputs, and don’t have any internal state that affects the output produced for a given input. Well-known functional languages include the ML family (Standard ML, OCaml, and other variants) and Haskell.</li> </ul> <p>The designers of some computer languages choose to emphasize one particular approach to programming. This often makes it difficult to write programs that use a different approach. Other languages are multi-paradigm languages that support several different approaches. Lisp, C++, and Python are multi-paradigm; you can write programs or libraries that are largely procedural, object-oriented, or functional in all of these languages. In a large program, different sections might be written using different approaches; the GUI might be object-oriented while the processing logic is procedural or functional, for example.</p> <p>In a functional program, input flows through a set of functions. Each function operates on its input and produces some output. Functional style discourages functions with side effects that modify internal state or make other changes that aren’t visible in the function’s return value. Functions that have no side effects at all are called <strong>purely functional</strong>. Avoiding side effects means not using data structures that get updated as a program runs; every function’s output must only depend on its input.</p> <p>Some languages are very strict about purity and don’t even have assignment statements such as <tt class="docutils literal"><span class="pre">a=3</span></tt> or <tt class="docutils literal"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">a</span> <span class="pre">+</span> <span class="pre">b</span></tt>, but it’s difficult to avoid all side effects. Printing to the screen or writing to a disk file are side effects, for example. For example, in Python a <tt class="docutils literal"><span class="pre">print</span></tt> statement or a <tt class="docutils literal"><span class="pre">time.sleep(1)</span></tt> both return no useful value; they’re only called for their side effects of sending some text to the screen or pausing execution for a second.</p> <p>Python programs written in functional style usually won’t go to the extreme of avoiding all I/O or all assignments; instead, they’ll provide a functional-appearing interface but will use non-functional features internally. For example, the implementation of a function will still use assignments to local variables, but won’t modify global variables or have other side effects.</p> <p>Functional programming can be considered the opposite of object-oriented programming. Objects are little capsules containing some internal state along with a collection of method calls that let you modify this state, and programs consist of making the right set of state changes. Functional programming wants to avoid state changes as much as possible and works with data flowing between functions. In Python you might combine the two approaches by writing functions that take and return instances representing objects in your application (e-mail messages, transactions, etc.).</p> <p>Functional design may seem like an odd constraint to work under. Why should you avoid objects and side effects? There are theoretical and practical advantages to the functional style:</p> <ul class="simple"> <li>Formal provability.</li> <li>Modularity.</li> <li>Composability.</li> <li>Ease of debugging and testing.</li> </ul> <div class="section" id="formal-provability"> <h3>Formal provability<a class="headerlink" href="#formal-provability" title="Permalink to this headline">¶</a></h3> <p>A theoretical benefit is that it’s easier to construct a mathematical proof that a functional program is correct.</p> <p>For a long time researchers have been interested in finding ways to mathematically prove programs correct. This is different from testing a program on numerous inputs and concluding that its output is usually correct, or reading a program’s source code and concluding that the code looks right; the goal is instead a rigorous proof that a program produces the right result for all possible inputs.</p> <p>The technique used to prove programs correct is to write down <strong>invariants</strong>, properties of the input data and of the program’s variables that are always true. For each line of code, you then show that if invariants X and Y are true <strong>before</strong> the line is executed, the slightly different invariants X’ and Y’ are true <strong>after</strong> the line is executed. This continues until you reach the end of the program, at which point the invariants should match the desired conditions on the program’s output.</p> <p>Functional programming’s avoidance of assignments arose because assignments are difficult to handle with this technique; assignments can break invariants that were true before the assignment without producing any new invariants that can be propagated onward.</p> <p>Unfortunately, proving programs correct is largely impractical and not relevant to Python software. Even trivial programs require proofs that are several pages long; the proof of correctness for a moderately complicated program would be enormous, and few or none of the programs you use daily (the Python interpreter, your XML parser, your web browser) could be proven correct. Even if you wrote down or generated a proof, there would then be the question of verifying the proof; maybe there’s an error in it, and you wrongly believe you’ve proved the program correct.</p> </div> <div class="section" id="modularity"> <h3>Modularity<a class="headerlink" href="#modularity" title="Permalink to this headline">¶</a></h3> <p>A more practical benefit of functional programming is that it forces you to break apart your problem into small pieces. Programs are more modular as a result. It’s easier to specify and write a small function that does one thing than a large function that performs a complicated transformation. Small functions are also easier to read and to check for errors.</p> </div> <div class="section" id="ease-of-debugging-and-testing"> <h3>Ease of debugging and testing<a class="headerlink" href="#ease-of-debugging-and-testing" title="Permalink to this headline">¶</a></h3> <p>Testing and debugging a functional-style program is easier.</p> <p>Debugging is simplified because functions are generally small and clearly specified. When a program doesn’t work, each function is an interface point where you can check that the data are correct. You can look at the intermediate inputs and outputs to quickly isolate the function that’s responsible for a bug.</p> <p>Testing is easier because each function is a potential subject for a unit test. Functions don’t depend on system state that needs to be replicated before running a test; instead you only have to synthesize the right input and then check that the output matches expectations.</p> </div> <div class="section" id="composability"> <h3>Composability<a class="headerlink" href="#composability" title="Permalink to this headline">¶</a></h3> <p>As you work on a functional-style program, you’ll write a number of functions with varying inputs and outputs. Some of these functions will be unavoidably specialized to a particular application, but others will be useful in a wide variety of programs. For example, a function that takes a directory path and returns all the XML files in the directory, or a function that takes a filename and returns its contents, can be applied to many different situations.</p> <p>Over time you’ll form a personal library of utilities. Often you’ll assemble new programs by arranging existing functions in a new configuration and writing a few functions specialized for the current task.</p> </div> </div> <div class="section" id="iterators"> <h2>Iterators<a class="headerlink" href="#iterators" title="Permalink to this headline">¶</a></h2> <p>I’ll start by looking at a Python language feature that’s an important foundation for writing functional-style programs: iterators.</p> <p>An iterator is an object representing a stream of data; this object returns the data one element at a time. A Python iterator must support a method called <tt class="docutils literal"><span class="pre">next()</span></tt> that takes no arguments and always returns the next element of the stream. If there are no more elements in the stream, <tt class="docutils literal"><span class="pre">next()</span></tt> must raise the <tt class="docutils literal"><span class="pre">StopIteration</span></tt> exception. Iterators don’t have to be finite, though; it’s perfectly reasonable to write an iterator that produces an infinite stream of data.</p> <p>The built-in <a class="reference internal" href="../library/functions.html#iter" title="iter"><tt class="xref py py-func docutils literal"><span class="pre">iter()</span></tt></a> function takes an arbitrary object and tries to return an iterator that will return the object’s contents or elements, raising <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> if the object doesn’t support iteration. Several of Python’s built-in data types support iteration, the most common being lists and dictionaries. An object is called an <strong>iterable</strong> object if you can get an iterator for it.</p> <p>You can experiment with the iteration interface manually:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span> <span class="gp">>>> </span><span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">L</span><span class="p">)</span> <span class="gp">>>> </span><span class="k">print</span> <span class="n">it</span> <span class="go"><...iterator object at ...></span> <span class="gp">>>> </span><span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span> <span class="go">1</span> <span class="gp">>>> </span><span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span> <span class="go">2</span> <span class="gp">>>> </span><span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span> <span class="go">3</span> <span class="gp">>>> </span><span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n">?</span> <span class="gr">StopIteration</span> <span class="go">>>></span> </pre></div> </div> <p>Python expects iterable objects in several different contexts, the most important being the <tt class="docutils literal"><span class="pre">for</span></tt> statement. In the statement <tt class="docutils literal"><span class="pre">for</span> <span class="pre">X</span> <span class="pre">in</span> <span class="pre">Y</span></tt>, Y must be an iterator or some object for which <tt class="docutils literal"><span class="pre">iter()</span></tt> can create an iterator. These two statements are equivalent:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">iter</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span> <span class="k">print</span> <span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">obj</span><span class="p">:</span> <span class="k">print</span> <span class="n">i</span> </pre></div> </div> <p>Iterators can be materialized as lists or tuples by using the <a class="reference internal" href="../library/functions.html#list" title="list"><tt class="xref py py-func docutils literal"><span class="pre">list()</span></tt></a> or <a class="reference internal" href="../library/functions.html#tuple" title="tuple"><tt class="xref py py-func docutils literal"><span class="pre">tuple()</span></tt></a> constructor functions:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span> <span class="gp">>>> </span><span class="n">iterator</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">L</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">t</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">iterator</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">t</span> <span class="go">(1, 2, 3)</span> </pre></div> </div> <p>Sequence unpacking also supports iterators: if you know an iterator will return N elements, you can unpack them into an N-tuple:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span> <span class="gp">>>> </span><span class="n">iterator</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">L</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span> <span class="o">=</span> <span class="n">iterator</span> <span class="gp">>>> </span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span> <span class="go">(1, 2, 3)</span> </pre></div> </div> <p>Built-in functions such as <a class="reference internal" href="../library/functions.html#max" title="max"><tt class="xref py py-func docutils literal"><span class="pre">max()</span></tt></a> and <a class="reference internal" href="../library/functions.html#min" title="min"><tt class="xref py py-func docutils literal"><span class="pre">min()</span></tt></a> can take a single iterator argument and will return the largest or smallest element. The <tt class="docutils literal"><span class="pre">"in"</span></tt> and <tt class="docutils literal"><span class="pre">"not</span> <span class="pre">in"</span></tt> operators also support iterators: <tt class="docutils literal"><span class="pre">X</span> <span class="pre">in</span> <span class="pre">iterator</span></tt> is true if X is found in the stream returned by the iterator. You’ll run into obvious problems if the iterator is infinite; <tt class="docutils literal"><span class="pre">max()</span></tt>, <tt class="docutils literal"><span class="pre">min()</span></tt> will never return, and if the element X never appears in the stream, the <tt class="docutils literal"><span class="pre">"in"</span></tt> and <tt class="docutils literal"><span class="pre">"not</span> <span class="pre">in"</span></tt> operators won’t return either.</p> <p>Note that you can only go forward in an iterator; there’s no way to get the previous element, reset the iterator, or make a copy of it. Iterator objects can optionally provide these additional capabilities, but the iterator protocol only specifies the <tt class="docutils literal"><span class="pre">next()</span></tt> method. Functions may therefore consume all of the iterator’s output, and if you need to do something different with the same stream, you’ll have to create a new iterator.</p> <div class="section" id="data-types-that-support-iterators"> <h3>Data Types That Support Iterators<a class="headerlink" href="#data-types-that-support-iterators" title="Permalink to this headline">¶</a></h3> <p>We’ve already seen how lists and tuples support iterators. In fact, any Python sequence type, such as strings, will automatically support creation of an iterator.</p> <p>Calling <a class="reference internal" href="../library/functions.html#iter" title="iter"><tt class="xref py py-func docutils literal"><span class="pre">iter()</span></tt></a> on a dictionary returns an iterator that will loop over the dictionary’s keys:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="p">{</span><span class="s">'Jan'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s">'Feb'</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s">'Mar'</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s">'Apr'</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span> <span class="s">'May'</span><span class="p">:</span> <span class="mi">5</span><span class="p">,</span> <span class="s">'Jun'</span><span class="p">:</span> <span class="mi">6</span><span class="p">,</span> <span class="gp">... </span> <span class="s">'Jul'</span><span class="p">:</span> <span class="mi">7</span><span class="p">,</span> <span class="s">'Aug'</span><span class="p">:</span> <span class="mi">8</span><span class="p">,</span> <span class="s">'Sep'</span><span class="p">:</span> <span class="mi">9</span><span class="p">,</span> <span class="s">'Oct'</span><span class="p">:</span> <span class="mi">10</span><span class="p">,</span> <span class="s">'Nov'</span><span class="p">:</span> <span class="mi">11</span><span class="p">,</span> <span class="s">'Dec'</span><span class="p">:</span> <span class="mi">12</span><span class="p">}</span> <span class="gp">>>> </span><span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">m</span><span class="p">:</span> <span class="gp">... </span> <span class="k">print</span> <span class="n">key</span><span class="p">,</span> <span class="n">m</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="go">Mar 3</span> <span class="go">Feb 2</span> <span class="go">Aug 8</span> <span class="go">Sep 9</span> <span class="go">Apr 4</span> <span class="go">Jun 6</span> <span class="go">Jul 7</span> <span class="go">Jan 1</span> <span class="go">May 5</span> <span class="go">Nov 11</span> <span class="go">Dec 12</span> <span class="go">Oct 10</span> </pre></div> </div> <p>Note that the order is essentially random, because it’s based on the hash ordering of the objects in the dictionary.</p> <p>Applying <tt class="docutils literal"><span class="pre">iter()</span></tt> to a dictionary always loops over the keys, but dictionaries have methods that return other iterators. If you want to iterate over keys, values, or key/value pairs, you can explicitly call the <tt class="docutils literal"><span class="pre">iterkeys()</span></tt>, <tt class="docutils literal"><span class="pre">itervalues()</span></tt>, or <tt class="docutils literal"><span class="pre">iteritems()</span></tt> methods to get an appropriate iterator.</p> <p>The <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><tt class="xref py py-func docutils literal"><span class="pre">dict()</span></tt></a> constructor can accept an iterator that returns a finite stream of <tt class="docutils literal"><span class="pre">(key,</span> <span class="pre">value)</span></tt> tuples:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">L</span> <span class="o">=</span> <span class="p">[(</span><span class="s">'Italy'</span><span class="p">,</span> <span class="s">'Rome'</span><span class="p">),</span> <span class="p">(</span><span class="s">'France'</span><span class="p">,</span> <span class="s">'Paris'</span><span class="p">),</span> <span class="p">(</span><span class="s">'US'</span><span class="p">,</span> <span class="s">'Washington DC'</span><span class="p">)]</span> <span class="gp">>>> </span><span class="nb">dict</span><span class="p">(</span><span class="nb">iter</span><span class="p">(</span><span class="n">L</span><span class="p">))</span> <span class="go">{'Italy': 'Rome', 'US': 'Washington DC', 'France': 'Paris'}</span> </pre></div> </div> <p>Files also support iteration by calling the <tt class="docutils literal"><span class="pre">readline()</span></tt> method until there are no more lines in the file. This means you can read each line of a file like this:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">file</span><span class="p">:</span> <span class="c"># do something for each line</span> <span class="o">...</span> </pre></div> </div> <p>Sets can take their contents from an iterable and let you iterate over the set’s elements:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">S</span> <span class="o">=</span> <span class="nb">set</span><span class="p">((</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">13</span><span class="p">))</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">S</span><span class="p">:</span> <span class="k">print</span> <span class="n">i</span> </pre></div> </div> </div> </div> <div class="section" id="generator-expressions-and-list-comprehensions"> <h2>Generator expressions and list comprehensions<a class="headerlink" href="#generator-expressions-and-list-comprehensions" title="Permalink to this headline">¶</a></h2> <p>Two common operations on an iterator’s output are 1) performing some operation for every element, 2) selecting a subset of elements that meet some condition. For example, given a list of strings, you might want to strip off trailing whitespace from each line or extract all the strings containing a given substring.</p> <p>List comprehensions and generator expressions (short form: “listcomps” and “genexps”) are a concise notation for such operations, borrowed from the functional programming language Haskell (<a class="reference external" href="http://www.haskell.org/">http://www.haskell.org/</a>). You can strip all the whitespace from a stream of strings with the following code:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">line_list</span> <span class="o">=</span> <span class="p">[</span><span class="s">' line 1</span><span class="se">\n</span><span class="s">'</span><span class="p">,</span> <span class="s">'line 2 </span><span class="se">\n</span><span class="s">'</span><span class="p">,</span> <span class="o">...</span><span class="p">]</span> <span class="c"># Generator expression -- returns iterator</span> <span class="n">stripped_iter</span> <span class="o">=</span> <span class="p">(</span><span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">line_list</span><span class="p">)</span> <span class="c"># List comprehension -- returns list</span> <span class="n">stripped_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">line_list</span><span class="p">]</span> </pre></div> </div> <p>You can select only certain elements by adding an <tt class="docutils literal"><span class="pre">"if"</span></tt> condition:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">stripped_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">line_list</span> <span class="k">if</span> <span class="n">line</span> <span class="o">!=</span> <span class="s">""</span><span class="p">]</span> </pre></div> </div> <p>With a list comprehension, you get back a Python list; <tt class="docutils literal"><span class="pre">stripped_list</span></tt> is a list containing the resulting lines, not an iterator. Generator expressions return an iterator that computes the values as necessary, not needing to materialize all the values at once. This means that list comprehensions aren’t useful if you’re working with iterators that return an infinite stream or a very large amount of data. Generator expressions are preferable in these situations.</p> <p>Generator expressions are surrounded by parentheses (“()”) and list comprehensions are surrounded by square brackets (“[]”). Generator expressions have the form:</p> <div class="highlight-python"><pre>( expression for expr in sequence1 if condition1 for expr2 in sequence2 if condition2 for expr3 in sequence3 ... if condition3 for exprN in sequenceN if conditionN )</pre> </div> <p>Again, for a list comprehension only the outside brackets are different (square brackets instead of parentheses).</p> <p>The elements of the generated output will be the successive values of <tt class="docutils literal"><span class="pre">expression</span></tt>. The <tt class="docutils literal"><span class="pre">if</span></tt> clauses are all optional; if present, <tt class="docutils literal"><span class="pre">expression</span></tt> is only evaluated and added to the result when <tt class="docutils literal"><span class="pre">condition</span></tt> is true.</p> <p>Generator expressions always have to be written inside parentheses, but the parentheses signalling a function call also count. If you want to create an iterator that will be immediately passed to a function you can write:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">obj_total</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">obj</span><span class="o">.</span><span class="n">count</span> <span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">list_all_objects</span><span class="p">())</span> </pre></div> </div> <p>The <tt class="docutils literal"><span class="pre">for...in</span></tt> clauses contain the sequences to be iterated over. The sequences do not have to be the same length, because they are iterated over from left to right, <strong>not</strong> in parallel. For each element in <tt class="docutils literal"><span class="pre">sequence1</span></tt>, <tt class="docutils literal"><span class="pre">sequence2</span></tt> is looped over from the beginning. <tt class="docutils literal"><span class="pre">sequence3</span></tt> is then looped over for each resulting pair of elements from <tt class="docutils literal"><span class="pre">sequence1</span></tt> and <tt class="docutils literal"><span class="pre">sequence2</span></tt>.</p> <p>To put it another way, a list comprehension or generator expression is equivalent to the following Python code:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">expr1</span> <span class="ow">in</span> <span class="n">sequence1</span><span class="p">:</span> <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">condition1</span><span class="p">):</span> <span class="k">continue</span> <span class="c"># Skip this element</span> <span class="k">for</span> <span class="n">expr2</span> <span class="ow">in</span> <span class="n">sequence2</span><span class="p">:</span> <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">condition2</span><span class="p">):</span> <span class="k">continue</span> <span class="c"># Skip this element</span> <span class="o">...</span> <span class="k">for</span> <span class="n">exprN</span> <span class="ow">in</span> <span class="n">sequenceN</span><span class="p">:</span> <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">conditionN</span><span class="p">):</span> <span class="k">continue</span> <span class="c"># Skip this element</span> <span class="c"># Output the value of</span> <span class="c"># the expression.</span> </pre></div> </div> <p>This means that when there are multiple <tt class="docutils literal"><span class="pre">for...in</span></tt> clauses but no <tt class="docutils literal"><span class="pre">if</span></tt> clauses, the length of the resulting output will be equal to the product of the lengths of all the sequences. If you have two lists of length 3, the output list is 9 elements long:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">seq1</span> <span class="o">=</span> <span class="s">'abc'</span> <span class="gp">>>> </span><span class="n">seq2</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="p">[(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">seq1</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">seq2</span><span class="p">]</span> <span class="go">[('a', 1), ('a', 2), ('a', 3),</span> <span class="go"> ('b', 1), ('b', 2), ('b', 3),</span> <span class="go"> ('c', 1), ('c', 2), ('c', 3)]</span> </pre></div> </div> <p>To avoid introducing an ambiguity into Python’s grammar, if <tt class="docutils literal"><span class="pre">expression</span></tt> is creating a tuple, it must be surrounded with parentheses. The first list comprehension below is a syntax error, while the second one is correct:</p> <div class="highlight-python"><pre># Syntax error [ x,y for x in seq1 for y in seq2] # Correct [ (x,y) for x in seq1 for y in seq2]</pre> </div> </div> <div class="section" id="generators"> <h2>Generators<a class="headerlink" href="#generators" title="Permalink to this headline">¶</a></h2> <p>Generators are a special class of functions that simplify the task of writing iterators. Regular functions compute a value and return it, but generators return an iterator that returns a stream of values.</p> <p>You’re doubtless familiar with how regular function calls work in Python or C. When you call a function, it gets a private namespace where its local variables are created. When the function reaches a <tt class="docutils literal"><span class="pre">return</span></tt> statement, the local variables are destroyed and the value is returned to the caller. A later call to the same function creates a new private namespace and a fresh set of local variables. But, what if the local variables weren’t thrown away on exiting a function? What if you could later resume the function where it left off? This is what generators provide; they can be thought of as resumable functions.</p> <p>Here’s the simplest example of a generator function:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">generate_ints</span><span class="p">(</span><span class="n">N</span><span class="p">):</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">N</span><span class="p">):</span> <span class="k">yield</span> <span class="n">i</span> </pre></div> </div> <p>Any function containing a <tt class="docutils literal"><span class="pre">yield</span></tt> keyword is a generator function; this is detected by Python’s <a class="reference internal" href="../glossary.html#term-bytecode"><em class="xref std std-term">bytecode</em></a> compiler which compiles the function specially as a result.</p> <p>When you call a generator function, it doesn’t return a single value; instead it returns a generator object that supports the iterator protocol. On executing the <tt class="docutils literal"><span class="pre">yield</span></tt> expression, the generator outputs the value of <tt class="docutils literal"><span class="pre">i</span></tt>, similar to a <tt class="docutils literal"><span class="pre">return</span></tt> statement. The big difference between <tt class="docutils literal"><span class="pre">yield</span></tt> and a <tt class="docutils literal"><span class="pre">return</span></tt> statement is that on reaching a <tt class="docutils literal"><span class="pre">yield</span></tt> the generator’s state of execution is suspended and local variables are preserved. On the next call to the generator’s <tt class="docutils literal"><span class="pre">.next()</span></tt> method, the function will resume executing.</p> <p>Here’s a sample usage of the <tt class="docutils literal"><span class="pre">generate_ints()</span></tt> generator:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">gen</span> <span class="o">=</span> <span class="n">generate_ints</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">gen</span> <span class="go"><generator object generate_ints at ...></span> <span class="gp">>>> </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span> <span class="go">0</span> <span class="gp">>>> </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span> <span class="go">1</span> <span class="gp">>>> </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span> <span class="go">2</span> <span class="gp">>>> </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> File <span class="nb">"stdin"</span>, line <span class="m">1</span>, in <span class="n">?</span> File <span class="nb">"stdin"</span>, line <span class="m">2</span>, in <span class="n">generate_ints</span> <span class="gr">StopIteration</span> </pre></div> </div> <p>You could equally write <tt class="docutils literal"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span> <span class="pre">generate_ints(5)</span></tt>, or <tt class="docutils literal"><span class="pre">a,b,c</span> <span class="pre">=</span> <span class="pre">generate_ints(3)</span></tt>.</p> <p>Inside a generator function, the <tt class="docutils literal"><span class="pre">return</span></tt> statement can only be used without a value, and signals the end of the procession of values; after executing a <tt class="docutils literal"><span class="pre">return</span></tt> the generator cannot return any further values. <tt class="docutils literal"><span class="pre">return</span></tt> with a value, such as <tt class="docutils literal"><span class="pre">return</span> <span class="pre">5</span></tt>, is a syntax error inside a generator function. The end of the generator’s results can also be indicated by raising <tt class="docutils literal"><span class="pre">StopIteration</span></tt> manually, or by just letting the flow of execution fall off the bottom of the function.</p> <p>You could achieve the effect of generators manually by writing your own class and storing all the local variables of the generator as instance variables. For example, returning a list of integers could be done by setting <tt class="docutils literal"><span class="pre">self.count</span></tt> to 0, and having the <tt class="docutils literal"><span class="pre">next()</span></tt> method increment <tt class="docutils literal"><span class="pre">self.count</span></tt> and return it. However, for a moderately complicated generator, writing a corresponding class can be much messier.</p> <p>The test suite included with Python’s library, <tt class="docutils literal"><span class="pre">test_generators.py</span></tt>, contains a number of more interesting examples. Here’s one generator that implements an in-order traversal of a tree using generators recursively.</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># A recursive generator that generates Tree leaves in in-order.</span> <span class="k">def</span> <span class="nf">inorder</span><span class="p">(</span><span class="n">t</span><span class="p">):</span> <span class="k">if</span> <span class="n">t</span><span class="p">:</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">inorder</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">left</span><span class="p">):</span> <span class="k">yield</span> <span class="n">x</span> <span class="k">yield</span> <span class="n">t</span><span class="o">.</span><span class="n">label</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">inorder</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">right</span><span class="p">):</span> <span class="k">yield</span> <span class="n">x</span> </pre></div> </div> <p>Two other examples in <tt class="docutils literal"><span class="pre">test_generators.py</span></tt> produce solutions for the N-Queens problem (placing N queens on an NxN chess board so that no queen threatens another) and the Knight’s Tour (finding a route that takes a knight to every square of an NxN chessboard without visiting any square twice).</p> <div class="section" id="passing-values-into-a-generator"> <h3>Passing values into a generator<a class="headerlink" href="#passing-values-into-a-generator" title="Permalink to this headline">¶</a></h3> <p>In Python 2.4 and earlier, generators only produced output. Once a generator’s code was invoked to create an iterator, there was no way to pass any new information into the function when its execution is resumed. You could hack together this ability by making the generator look at a global variable or by passing in some mutable object that callers then modify, but these approaches are messy.</p> <p>In Python 2.5 there’s a simple way to pass values into a generator. <a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> became an expression, returning a value that can be assigned to a variable or otherwise operated on:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">val</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">i</span><span class="p">)</span> </pre></div> </div> <p>I recommend that you <strong>always</strong> put parentheses around a <tt class="docutils literal"><span class="pre">yield</span></tt> expression when you’re doing something with the returned value, as in the above example. The parentheses aren’t always necessary, but it’s easier to always add them instead of having to remember when they’re needed.</p> <p>(PEP 342 explains the exact rules, which are that a <tt class="docutils literal"><span class="pre">yield</span></tt>-expression must always be parenthesized except when it occurs at the top-level expression on the right-hand side of an assignment. This means you can write <tt class="docutils literal"><span class="pre">val</span> <span class="pre">=</span> <span class="pre">yield</span> <span class="pre">i</span></tt> but have to use parentheses when there’s an operation, as in <tt class="docutils literal"><span class="pre">val</span> <span class="pre">=</span> <span class="pre">(yield</span> <span class="pre">i)</span> <span class="pre">+</span> <span class="pre">12</span></tt>.)</p> <p>Values are sent into a generator by calling its <tt class="docutils literal"><span class="pre">send(value)</span></tt> method. This method resumes the generator’s code and the <tt class="docutils literal"><span class="pre">yield</span></tt> expression returns the specified value. If the regular <tt class="docutils literal"><span class="pre">next()</span></tt> method is called, the <tt class="docutils literal"><span class="pre">yield</span></tt> returns <tt class="docutils literal"><span class="pre">None</span></tt>.</p> <p>Here’s a simple counter that increments by 1 and allows changing the value of the internal counter.</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">counter</span> <span class="p">(</span><span class="n">maximum</span><span class="p">):</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span> <span class="k">while</span> <span class="n">i</span> <span class="o"><</span> <span class="n">maximum</span><span class="p">:</span> <span class="n">val</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">i</span><span class="p">)</span> <span class="c"># If value provided, change counter</span> <span class="k">if</span> <span class="n">val</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span> <span class="n">i</span> <span class="o">=</span> <span class="n">val</span> <span class="k">else</span><span class="p">:</span> <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span> </pre></div> </div> <p>And here’s an example of changing the counter:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">it</span> <span class="o">=</span> <span class="n">counter</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="gp">>>> </span><span class="k">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span> <span class="go">0</span> <span class="gp">>>> </span><span class="k">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span> <span class="go">1</span> <span class="gp">>>> </span><span class="k">print</span> <span class="n">it</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="mi">8</span><span class="p">)</span> <span class="go">8</span> <span class="gp">>>> </span><span class="k">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span> <span class="go">9</span> <span class="gp">>>> </span><span class="k">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> File <span class="nb">"t.py"</span>, line <span class="m">15</span>, in <span class="n">?</span> <span class="k">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span> <span class="gr">StopIteration</span> </pre></div> </div> <p>Because <tt class="docutils literal"><span class="pre">yield</span></tt> will often be returning <tt class="docutils literal"><span class="pre">None</span></tt>, you should always check for this case. Don’t just use its value in expressions unless you’re sure that the <tt class="docutils literal"><span class="pre">send()</span></tt> method will be the only method used resume your generator function.</p> <p>In addition to <tt class="docutils literal"><span class="pre">send()</span></tt>, there are two other new methods on generators:</p> <ul> <li><p class="first"><tt class="docutils literal"><span class="pre">throw(type,</span> <span class="pre">value=None,</span> <span class="pre">traceback=None)</span></tt> is used to raise an exception inside the generator; the exception is raised by the <tt class="docutils literal"><span class="pre">yield</span></tt> expression where the generator’s execution is paused.</p> </li> <li><p class="first"><tt class="docutils literal"><span class="pre">close()</span></tt> raises a <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><tt class="xref py py-exc docutils literal"><span class="pre">GeneratorExit</span></tt></a> exception inside the generator to terminate the iteration. On receiving this exception, the generator’s code must either raise <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><tt class="xref py py-exc docutils literal"><span class="pre">GeneratorExit</span></tt></a> or <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><tt class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></tt></a>; catching the exception and doing anything else is illegal and will trigger a <a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a>. <tt class="docutils literal"><span class="pre">close()</span></tt> will also be called by Python’s garbage collector when the generator is garbage-collected.</p> <p>If you need to run cleanup code when a <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><tt class="xref py py-exc docutils literal"><span class="pre">GeneratorExit</span></tt></a> occurs, I suggest using a <tt class="docutils literal"><span class="pre">try:</span> <span class="pre">...</span> <span class="pre">finally:</span></tt> suite instead of catching <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><tt class="xref py py-exc docutils literal"><span class="pre">GeneratorExit</span></tt></a>.</p> </li> </ul> <p>The cumulative effect of these changes is to turn generators from one-way producers of information into both producers and consumers.</p> <p>Generators also become <strong>coroutines</strong>, a more generalized form of subroutines. Subroutines are entered at one point and exited at another point (the top of the function, and a <tt class="docutils literal"><span class="pre">return</span></tt> statement), but coroutines can be entered, exited, and resumed at many different points (the <tt class="docutils literal"><span class="pre">yield</span></tt> statements).</p> </div> </div> <div class="section" id="built-in-functions"> <h2>Built-in functions<a class="headerlink" href="#built-in-functions" title="Permalink to this headline">¶</a></h2> <p>Let’s look in more detail at built-in functions often used with iterators.</p> <p>Two of Python’s built-in functions, <a class="reference internal" href="../library/functions.html#map" title="map"><tt class="xref py py-func docutils literal"><span class="pre">map()</span></tt></a> and <a class="reference internal" href="../library/functions.html#filter" title="filter"><tt class="xref py py-func docutils literal"><span class="pre">filter()</span></tt></a>, are somewhat obsolete; they duplicate the features of list comprehensions but return actual lists instead of iterators.</p> <p><tt class="docutils literal"><span class="pre">map(f,</span> <span class="pre">iterA,</span> <span class="pre">iterB,</span> <span class="pre">...)</span></tt> returns a list containing <tt class="docutils literal"><span class="pre">f(iterA[0],</span> <span class="pre">iterB[0]),</span> <span class="pre">f(iterA[1],</span> <span class="pre">iterB[1]),</span> <span class="pre">f(iterA[2],</span> <span class="pre">iterB[2]),</span> <span class="pre">...</span></tt>.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="k">def</span> <span class="nf">upper</span><span class="p">(</span><span class="n">s</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="n">s</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span> </pre></div> </div> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="nb">map</span><span class="p">(</span><span class="n">upper</span><span class="p">,</span> <span class="p">[</span><span class="s">'sentence'</span><span class="p">,</span> <span class="s">'fragment'</span><span class="p">])</span> <span class="go">['SENTENCE', 'FRAGMENT']</span> </pre></div> </div> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="p">[</span><span class="n">upper</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="p">[</span><span class="s">'sentence'</span><span class="p">,</span> <span class="s">'fragment'</span><span class="p">]]</span> <span class="go">['SENTENCE', 'FRAGMENT']</span> </pre></div> </div> <p>As shown above, you can achieve the same effect with a list comprehension. The <a class="reference internal" href="../library/itertools.html#itertools.imap" title="itertools.imap"><tt class="xref py py-func docutils literal"><span class="pre">itertools.imap()</span></tt></a> function does the same thing but can handle infinite iterators; it’ll be discussed later, in the section on the <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><tt class="xref py py-mod docutils literal"><span class="pre">itertools</span></tt></a> module.</p> <p><tt class="docutils literal"><span class="pre">filter(predicate,</span> <span class="pre">iter)</span></tt> returns a list that contains all the sequence elements that meet a certain condition, and is similarly duplicated by list comprehensions. A <strong>predicate</strong> is a function that returns the truth value of some condition; for use with <a class="reference internal" href="../library/functions.html#filter" title="filter"><tt class="xref py py-func docutils literal"><span class="pre">filter()</span></tt></a>, the predicate must take a single value.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="k">def</span> <span class="nf">is_even</span><span class="p">(</span><span class="n">x</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="p">(</span><span class="n">x</span> <span class="o">%</span> <span class="mi">2</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span> </pre></div> </div> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="nb">filter</span><span class="p">(</span><span class="n">is_even</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span> <span class="go">[0, 2, 4, 6, 8]</span> </pre></div> </div> <p>This can also be written as a list comprehension:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="p">[</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="k">if</span> <span class="n">is_even</span><span class="p">(</span><span class="n">x</span><span class="p">)]</span> <span class="go">[0, 2, 4, 6, 8]</span> </pre></div> </div> <p><a class="reference internal" href="../library/functions.html#filter" title="filter"><tt class="xref py py-func docutils literal"><span class="pre">filter()</span></tt></a> also has a counterpart in the <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><tt class="xref py py-mod docutils literal"><span class="pre">itertools</span></tt></a> module, <a class="reference internal" href="../library/itertools.html#itertools.ifilter" title="itertools.ifilter"><tt class="xref py py-func docutils literal"><span class="pre">itertools.ifilter()</span></tt></a>, that returns an iterator and can therefore handle infinite sequences just as <a class="reference internal" href="../library/itertools.html#itertools.imap" title="itertools.imap"><tt class="xref py py-func docutils literal"><span class="pre">itertools.imap()</span></tt></a> can.</p> <p><tt class="docutils literal"><span class="pre">reduce(func,</span> <span class="pre">iter,</span> <span class="pre">[initial_value])</span></tt> doesn’t have a counterpart in the <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><tt class="xref py py-mod docutils literal"><span class="pre">itertools</span></tt></a> module because it cumulatively performs an operation on all the iterable’s elements and therefore can’t be applied to infinite iterables. <tt class="docutils literal"><span class="pre">func</span></tt> must be a function that takes two elements and returns a single value. <a class="reference internal" href="../library/functions.html#reduce" title="reduce"><tt class="xref py py-func docutils literal"><span class="pre">reduce()</span></tt></a> takes the first two elements A and B returned by the iterator and calculates <tt class="docutils literal"><span class="pre">func(A,</span> <span class="pre">B)</span></tt>. It then requests the third element, C, calculates <tt class="docutils literal"><span class="pre">func(func(A,</span> <span class="pre">B),</span> <span class="pre">C)</span></tt>, combines this result with the fourth element returned, and continues until the iterable is exhausted. If the iterable returns no values at all, a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> exception is raised. If the initial value is supplied, it’s used as a starting point and <tt class="docutils literal"><span class="pre">func(initial_value,</span> <span class="pre">A)</span></tt> is the first calculation.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">operator</span> <span class="gp">>>> </span><span class="nb">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">concat</span><span class="p">,</span> <span class="p">[</span><span class="s">'A'</span><span class="p">,</span> <span class="s">'BB'</span><span class="p">,</span> <span class="s">'C'</span><span class="p">])</span> <span class="go">'ABBC'</span> <span class="gp">>>> </span><span class="nb">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">concat</span><span class="p">,</span> <span class="p">[])</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">TypeError</span>: <span class="n">reduce() of empty sequence with no initial value</span> <span class="gp">>>> </span><span class="nb">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">mul</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="mi">1</span><span class="p">)</span> <span class="go">6</span> <span class="gp">>>> </span><span class="nb">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">mul</span><span class="p">,</span> <span class="p">[],</span> <span class="mi">1</span><span class="p">)</span> <span class="go">1</span> </pre></div> </div> <p>If you use <a class="reference internal" href="../library/operator.html#operator.add" title="operator.add"><tt class="xref py py-func docutils literal"><span class="pre">operator.add()</span></tt></a> with <a class="reference internal" href="../library/functions.html#reduce" title="reduce"><tt class="xref py py-func docutils literal"><span class="pre">reduce()</span></tt></a>, you’ll add up all the elements of the iterable. This case is so common that there’s a special built-in called <a class="reference internal" href="../library/functions.html#sum" title="sum"><tt class="xref py py-func docutils literal"><span class="pre">sum()</span></tt></a> to compute it:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="nb">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">add</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">],</span> <span class="mi">0</span><span class="p">)</span> <span class="go">10</span> <span class="gp">>>> </span><span class="nb">sum</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">])</span> <span class="go">10</span> <span class="gp">>>> </span><span class="nb">sum</span><span class="p">([])</span> <span class="go">0</span> </pre></div> </div> <p>For many uses of <a class="reference internal" href="../library/functions.html#reduce" title="reduce"><tt class="xref py py-func docutils literal"><span class="pre">reduce()</span></tt></a>, though, it can be clearer to just write the obvious <a class="reference internal" href="../reference/compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a> loop:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># Instead of:</span> <span class="n">product</span> <span class="o">=</span> <span class="nb">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">mul</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="mi">1</span><span class="p">)</span> <span class="c"># You can write:</span> <span class="n">product</span> <span class="o">=</span> <span class="mi">1</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]:</span> <span class="n">product</span> <span class="o">*=</span> <span class="n">i</span> </pre></div> </div> <p><tt class="docutils literal"><span class="pre">enumerate(iter)</span></tt> counts off the elements in the iterable, returning 2-tuples containing the count and each element.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">([</span><span class="s">'subject'</span><span class="p">,</span> <span class="s">'verb'</span><span class="p">,</span> <span class="s">'object'</span><span class="p">]):</span> <span class="gp">... </span> <span class="k">print</span> <span class="n">item</span> <span class="go">(0, 'subject')</span> <span class="go">(1, 'verb')</span> <span class="go">(2, 'object')</span> </pre></div> </div> <p><a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><tt class="xref py py-func docutils literal"><span class="pre">enumerate()</span></tt></a> is often used when looping through a list and recording the indexes at which certain conditions are met:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s">'data.txt'</span><span class="p">,</span> <span class="s">'r'</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">f</span><span class="p">):</span> <span class="k">if</span> <span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="o">==</span> <span class="s">''</span><span class="p">:</span> <span class="k">print</span> <span class="s">'Blank line at line #</span><span class="si">%i</span><span class="s">'</span> <span class="o">%</span> <span class="n">i</span> </pre></div> </div> <p><tt class="docutils literal"><span class="pre">sorted(iterable,</span> <span class="pre">[cmp=None],</span> <span class="pre">[key=None],</span> <span class="pre">[reverse=False])</span></tt> collects all the elements of the iterable into a list, sorts the list, and returns the sorted result. The <tt class="docutils literal"><span class="pre">cmp</span></tt>, <tt class="docutils literal"><span class="pre">key</span></tt>, and <tt class="docutils literal"><span class="pre">reverse</span></tt> arguments are passed through to the constructed list’s <tt class="docutils literal"><span class="pre">.sort()</span></tt> method.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">random</span> <span class="gp">>>> </span><span class="c"># Generate 8 random numbers between [0, 10000)</span> <span class="gp">>>> </span><span class="n">rand_list</span> <span class="o">=</span> <span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10000</span><span class="p">),</span> <span class="mi">8</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">rand_list</span> <span class="go">[769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">rand_list</span><span class="p">)</span> <span class="go">[769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">rand_list</span><span class="p">,</span> <span class="n">reverse</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="go">[9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]</span> </pre></div> </div> <p>(For a more detailed discussion of sorting, see the Sorting mini-HOWTO in the Python wiki at <a class="reference external" href="http://wiki.python.org/moin/HowTo/Sorting">http://wiki.python.org/moin/HowTo/Sorting</a>.)</p> <p>The <tt class="docutils literal"><span class="pre">any(iter)</span></tt> and <tt class="docutils literal"><span class="pre">all(iter)</span></tt> built-ins look at the truth values of an iterable’s contents. <a class="reference internal" href="../library/functions.html#any" title="any"><tt class="xref py py-func docutils literal"><span class="pre">any()</span></tt></a> returns True if any element in the iterable is a true value, and <a class="reference internal" href="../library/functions.html#all" title="all"><tt class="xref py py-func docutils literal"><span class="pre">all()</span></tt></a> returns True if all of the elements are true values:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="nb">any</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">])</span> <span class="go">True</span> <span class="gp">>>> </span><span class="nb">any</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">])</span> <span class="go">False</span> <span class="gp">>>> </span><span class="nb">any</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">])</span> <span class="go">True</span> <span class="gp">>>> </span><span class="nb">all</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">])</span> <span class="go">False</span> <span class="gp">>>> </span><span class="nb">all</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">])</span> <span class="go">False</span> <span class="gp">>>> </span><span class="nb">all</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">])</span> <span class="go">True</span> </pre></div> </div> </div> <div class="section" id="small-functions-and-the-lambda-expression"> <h2>Small functions and the lambda expression<a class="headerlink" href="#small-functions-and-the-lambda-expression" title="Permalink to this headline">¶</a></h2> <p>When writing functional-style programs, you’ll often need little functions that act as predicates or that combine elements in some way.</p> <p>If there’s a Python built-in or a module function that’s suitable, you don’t need to define a new function at all:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">stripped_lines</span> <span class="o">=</span> <span class="p">[</span><span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">lines</span><span class="p">]</span> <span class="n">existing_files</span> <span class="o">=</span> <span class="nb">filter</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">,</span> <span class="n">file_list</span><span class="p">)</span> </pre></div> </div> <p>If the function you need doesn’t exist, you need to write it. One way to write small functions is to use the <tt class="docutils literal"><span class="pre">lambda</span></tt> statement. <tt class="docutils literal"><span class="pre">lambda</span></tt> takes a number of parameters and an expression combining these parameters, and creates a small function that returns the value of the expression:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">lowercase</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span> <span class="n">print_assign</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">name</span><span class="p">,</span> <span class="n">value</span><span class="p">:</span> <span class="n">name</span> <span class="o">+</span> <span class="s">'='</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">value</span><span class="p">)</span> <span class="n">adder</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">:</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span> </pre></div> </div> <p>An alternative is to just use the <tt class="docutils literal"><span class="pre">def</span></tt> statement and define a function in the usual way:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">lowercase</span><span class="p">(</span><span class="n">x</span><span class="p">):</span> <span class="k">return</span> <span class="n">x</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span> <span class="k">def</span> <span class="nf">print_assign</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="k">return</span> <span class="n">name</span> <span class="o">+</span> <span class="s">'='</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">value</span><span class="p">)</span> <span class="k">def</span> <span class="nf">adder</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">):</span> <span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span> </pre></div> </div> <p>Which alternative is preferable? That’s a style question; my usual course is to avoid using <tt class="docutils literal"><span class="pre">lambda</span></tt>.</p> <p>One reason for my preference is that <tt class="docutils literal"><span class="pre">lambda</span></tt> is quite limited in the functions it can define. The result has to be computable as a single expression, which means you can’t have multiway <tt class="docutils literal"><span class="pre">if...</span> <span class="pre">elif...</span> <span class="pre">else</span></tt> comparisons or <tt class="docutils literal"><span class="pre">try...</span> <span class="pre">except</span></tt> statements. If you try to do too much in a <tt class="docutils literal"><span class="pre">lambda</span></tt> statement, you’ll end up with an overly complicated expression that’s hard to read. Quick, what’s the following code doing?</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">total</span> <span class="o">=</span> <span class="nb">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="n">b</span><span class="p">[</span><span class="mi">1</span><span class="p">]),</span> <span class="n">items</span><span class="p">)[</span><span class="mi">1</span><span class="p">]</span> </pre></div> </div> <p>You can figure it out, but it takes time to disentangle the expression to figure out what’s going on. Using a short nested <tt class="docutils literal"><span class="pre">def</span></tt> statements makes things a little bit better:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">combine</span> <span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span> <span class="k">return</span> <span class="mi">0</span><span class="p">,</span> <span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="n">b</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="n">total</span> <span class="o">=</span> <span class="nb">reduce</span><span class="p">(</span><span class="n">combine</span><span class="p">,</span> <span class="n">items</span><span class="p">)[</span><span class="mi">1</span><span class="p">]</span> </pre></div> </div> <p>But it would be best of all if I had simply used a <tt class="docutils literal"><span class="pre">for</span></tt> loop:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">total</span> <span class="o">=</span> <span class="mi">0</span> <span class="k">for</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="ow">in</span> <span class="n">items</span><span class="p">:</span> <span class="n">total</span> <span class="o">+=</span> <span class="n">b</span> </pre></div> </div> <p>Or the <a class="reference internal" href="../library/functions.html#sum" title="sum"><tt class="xref py py-func docutils literal"><span class="pre">sum()</span></tt></a> built-in and a generator expression:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">total</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">b</span> <span class="k">for</span> <span class="n">a</span><span class="p">,</span><span class="n">b</span> <span class="ow">in</span> <span class="n">items</span><span class="p">)</span> </pre></div> </div> <p>Many uses of <a class="reference internal" href="../library/functions.html#reduce" title="reduce"><tt class="xref py py-func docutils literal"><span class="pre">reduce()</span></tt></a> are clearer when written as <tt class="docutils literal"><span class="pre">for</span></tt> loops.</p> <p>Fredrik Lundh once suggested the following set of rules for refactoring uses of <tt class="docutils literal"><span class="pre">lambda</span></tt>:</p> <ol class="arabic simple"> <li>Write a lambda function.</li> <li>Write a comment explaining what the heck that lambda does.</li> <li>Study the comment for a while, and think of a name that captures the essence of the comment.</li> <li>Convert the lambda to a def statement, using that name.</li> <li>Remove the comment.</li> </ol> <p>I really like these rules, but you’re free to disagree about whether this lambda-free style is better.</p> </div> <div class="section" id="the-itertools-module"> <h2>The itertools module<a class="headerlink" href="#the-itertools-module" title="Permalink to this headline">¶</a></h2> <p>The <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><tt class="xref py py-mod docutils literal"><span class="pre">itertools</span></tt></a> module contains a number of commonly-used iterators as well as functions for combining several iterators. This section will introduce the module’s contents by showing small examples.</p> <p>The module’s functions fall into a few broad classes:</p> <ul class="simple"> <li>Functions that create a new iterator based on an existing iterator.</li> <li>Functions for treating an iterator’s elements as function arguments.</li> <li>Functions for selecting portions of an iterator’s output.</li> <li>A function for grouping an iterator’s output.</li> </ul> <div class="section" id="creating-new-iterators"> <h3>Creating new iterators<a class="headerlink" href="#creating-new-iterators" title="Permalink to this headline">¶</a></h3> <p><tt class="docutils literal"><span class="pre">itertools.count(n)</span></tt> returns an infinite stream of integers, increasing by 1 each time. You can optionally supply the starting number, which defaults to 0:</p> <div class="highlight-python"><pre>itertools.count() => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... itertools.count(10) => 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...</pre> </div> <p><tt class="docutils literal"><span class="pre">itertools.cycle(iter)</span></tt> saves a copy of the contents of a provided iterable and returns a new iterator that returns its elements from first to last. The new iterator will repeat these elements infinitely.</p> <div class="highlight-python"><pre>itertools.cycle([1,2,3,4,5]) => 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...</pre> </div> <p><tt class="docutils literal"><span class="pre">itertools.repeat(elem,</span> <span class="pre">[n])</span></tt> returns the provided element <tt class="docutils literal"><span class="pre">n</span></tt> times, or returns the element endlessly if <tt class="docutils literal"><span class="pre">n</span></tt> is not provided.</p> <div class="highlight-python"><pre>itertools.repeat('abc') => abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ... itertools.repeat('abc', 5) => abc, abc, abc, abc, abc</pre> </div> <p><tt class="docutils literal"><span class="pre">itertools.chain(iterA,</span> <span class="pre">iterB,</span> <span class="pre">...)</span></tt> takes an arbitrary number of iterables as input, and returns all the elements of the first iterator, then all the elements of the second, and so on, until all of the iterables have been exhausted.</p> <div class="highlight-python"><pre>itertools.chain(['a', 'b', 'c'], (1, 2, 3)) => a, b, c, 1, 2, 3</pre> </div> <p><tt class="docutils literal"><span class="pre">itertools.izip(iterA,</span> <span class="pre">iterB,</span> <span class="pre">...)</span></tt> takes one element from each iterable and returns them in a tuple:</p> <div class="highlight-python"><pre>itertools.izip(['a', 'b', 'c'], (1, 2, 3)) => ('a', 1), ('b', 2), ('c', 3)</pre> </div> <p>It’s similar to the built-in <a class="reference internal" href="../library/functions.html#zip" title="zip"><tt class="xref py py-func docutils literal"><span class="pre">zip()</span></tt></a> function, but doesn’t construct an in-memory list and exhaust all the input iterators before returning; instead tuples are constructed and returned only if they’re requested. (The technical term for this behaviour is <a class="reference external" href="http://en.wikipedia.org/wiki/Lazy_evaluation">lazy evaluation</a>.)</p> <p>This iterator is intended to be used with iterables that are all of the same length. If the iterables are of different lengths, the resulting stream will be the same length as the shortest iterable.</p> <div class="highlight-python"><pre>itertools.izip(['a', 'b'], (1, 2, 3)) => ('a', 1), ('b', 2)</pre> </div> <p>You should avoid doing this, though, because an element may be taken from the longer iterators and discarded. This means you can’t go on to use the iterators further because you risk skipping a discarded element.</p> <p><tt class="docutils literal"><span class="pre">itertools.islice(iter,</span> <span class="pre">[start],</span> <span class="pre">stop,</span> <span class="pre">[step])</span></tt> returns a stream that’s a slice of the iterator. With a single <tt class="docutils literal"><span class="pre">stop</span></tt> argument, it will return the first <tt class="docutils literal"><span class="pre">stop</span></tt> elements. If you supply a starting index, you’ll get <tt class="docutils literal"><span class="pre">stop-start</span></tt> elements, and if you supply a value for <tt class="docutils literal"><span class="pre">step</span></tt>, elements will be skipped accordingly. Unlike Python’s string and list slicing, you can’t use negative values for <tt class="docutils literal"><span class="pre">start</span></tt>, <tt class="docutils literal"><span class="pre">stop</span></tt>, or <tt class="docutils literal"><span class="pre">step</span></tt>.</p> <div class="highlight-python"><pre>itertools.islice(range(10), 8) => 0, 1, 2, 3, 4, 5, 6, 7 itertools.islice(range(10), 2, 8) => 2, 3, 4, 5, 6, 7 itertools.islice(range(10), 2, 8, 2) => 2, 4, 6</pre> </div> <p><tt class="docutils literal"><span class="pre">itertools.tee(iter,</span> <span class="pre">[n])</span></tt> replicates an iterator; it returns <tt class="docutils literal"><span class="pre">n</span></tt> independent iterators that will all return the contents of the source iterator. If you don’t supply a value for <tt class="docutils literal"><span class="pre">n</span></tt>, the default is 2. Replicating iterators requires saving some of the contents of the source iterator, so this can consume significant memory if the iterator is large and one of the new iterators is consumed more than the others.</p> <div class="highlight-python"><pre>itertools.tee( itertools.count() ) => iterA, iterB where iterA -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... and iterB -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...</pre> </div> </div> <div class="section" id="calling-functions-on-elements"> <h3>Calling functions on elements<a class="headerlink" href="#calling-functions-on-elements" title="Permalink to this headline">¶</a></h3> <p>Two functions are used for calling other functions on the contents of an iterable.</p> <p><tt class="docutils literal"><span class="pre">itertools.imap(f,</span> <span class="pre">iterA,</span> <span class="pre">iterB,</span> <span class="pre">...)</span></tt> returns a stream containing <tt class="docutils literal"><span class="pre">f(iterA[0],</span> <span class="pre">iterB[0]),</span> <span class="pre">f(iterA[1],</span> <span class="pre">iterB[1]),</span> <span class="pre">f(iterA[2],</span> <span class="pre">iterB[2]),</span> <span class="pre">...</span></tt>:</p> <div class="highlight-python"><pre>itertools.imap(operator.add, [5, 6, 5], [1, 2, 3]) => 6, 8, 8</pre> </div> <p>The <tt class="docutils literal"><span class="pre">operator</span></tt> module contains a set of functions corresponding to Python’s operators. Some examples are <tt class="docutils literal"><span class="pre">operator.add(a,</span> <span class="pre">b)</span></tt> (adds two values), <tt class="docutils literal"><span class="pre">operator.ne(a,</span> <span class="pre">b)</span></tt> (same as <tt class="docutils literal"><span class="pre">a!=b</span></tt>), and <tt class="docutils literal"><span class="pre">operator.attrgetter('id')</span></tt> (returns a callable that fetches the <tt class="docutils literal"><span class="pre">"id"</span></tt> attribute).</p> <p><tt class="docutils literal"><span class="pre">itertools.starmap(func,</span> <span class="pre">iter)</span></tt> assumes that the iterable will return a stream of tuples, and calls <tt class="docutils literal"><span class="pre">f()</span></tt> using these tuples as the arguments:</p> <div class="highlight-python"><pre>itertools.starmap(os.path.join, [('/usr', 'bin', 'java'), ('/bin', 'python'), ('/usr', 'bin', 'perl'),('/usr', 'bin', 'ruby')]) => /usr/bin/java, /bin/python, /usr/bin/perl, /usr/bin/ruby</pre> </div> </div> <div class="section" id="selecting-elements"> <h3>Selecting elements<a class="headerlink" href="#selecting-elements" title="Permalink to this headline">¶</a></h3> <p>Another group of functions chooses a subset of an iterator’s elements based on a predicate.</p> <p><tt class="docutils literal"><span class="pre">itertools.ifilter(predicate,</span> <span class="pre">iter)</span></tt> returns all the elements for which the predicate returns true:</p> <div class="highlight-python"><pre>def is_even(x): return (x % 2) == 0 itertools.ifilter(is_even, itertools.count()) => 0, 2, 4, 6, 8, 10, 12, 14, ...</pre> </div> <p><tt class="docutils literal"><span class="pre">itertools.ifilterfalse(predicate,</span> <span class="pre">iter)</span></tt> is the opposite, returning all elements for which the predicate returns false:</p> <div class="highlight-python"><pre>itertools.ifilterfalse(is_even, itertools.count()) => 1, 3, 5, 7, 9, 11, 13, 15, ...</pre> </div> <p><tt class="docutils literal"><span class="pre">itertools.takewhile(predicate,</span> <span class="pre">iter)</span></tt> returns elements for as long as the predicate returns true. Once the predicate returns false, the iterator will signal the end of its results.</p> <div class="highlight-python"><pre>def less_than_10(x): return (x < 10) itertools.takewhile(less_than_10, itertools.count()) => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 itertools.takewhile(is_even, itertools.count()) => 0</pre> </div> <p><tt class="docutils literal"><span class="pre">itertools.dropwhile(predicate,</span> <span class="pre">iter)</span></tt> discards elements while the predicate returns true, and then returns the rest of the iterable’s results.</p> <div class="highlight-python"><pre>itertools.dropwhile(less_than_10, itertools.count()) => 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... itertools.dropwhile(is_even, itertools.count()) => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...</pre> </div> </div> <div class="section" id="grouping-elements"> <h3>Grouping elements<a class="headerlink" href="#grouping-elements" title="Permalink to this headline">¶</a></h3> <p>The last function I’ll discuss, <tt class="docutils literal"><span class="pre">itertools.groupby(iter,</span> <span class="pre">key_func=None)</span></tt>, is the most complicated. <tt class="docutils literal"><span class="pre">key_func(elem)</span></tt> is a function that can compute a key value for each element returned by the iterable. If you don’t supply a key function, the key is simply each element itself.</p> <p><tt class="docutils literal"><span class="pre">groupby()</span></tt> collects all the consecutive elements from the underlying iterable that have the same key value, and returns a stream of 2-tuples containing a key value and an iterator for the elements with that key.</p> <div class="highlight-python"><pre>city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'), ('Anchorage', 'AK'), ('Nome', 'AK'), ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'), ... ] def get_state ((city, state)): return state itertools.groupby(city_list, get_state) => ('AL', iterator-1), ('AK', iterator-2), ('AZ', iterator-3), ... where iterator-1 => ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL') iterator-2 => ('Anchorage', 'AK'), ('Nome', 'AK') iterator-3 => ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')</pre> </div> <p><tt class="docutils literal"><span class="pre">groupby()</span></tt> assumes that the underlying iterable’s contents will already be sorted based on the key. Note that the returned iterators also use the underlying iterable, so you have to consume the results of iterator-1 before requesting iterator-2 and its corresponding key.</p> </div> </div> <div class="section" id="the-functools-module"> <h2>The functools module<a class="headerlink" href="#the-functools-module" title="Permalink to this headline">¶</a></h2> <p>The <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><tt class="xref py py-mod docutils literal"><span class="pre">functools</span></tt></a> module in Python 2.5 contains some higher-order functions. A <strong>higher-order function</strong> takes one or more functions as input and returns a new function. The most useful tool in this module is the <a class="reference internal" href="../library/functools.html#functools.partial" title="functools.partial"><tt class="xref py py-func docutils literal"><span class="pre">functools.partial()</span></tt></a> function.</p> <p>For programs written in a functional style, you’ll sometimes want to construct variants of existing functions that have some of the parameters filled in. Consider a Python function <tt class="docutils literal"><span class="pre">f(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></tt>; you may wish to create a new function <tt class="docutils literal"><span class="pre">g(b,</span> <span class="pre">c)</span></tt> that’s equivalent to <tt class="docutils literal"><span class="pre">f(1,</span> <span class="pre">b,</span> <span class="pre">c)</span></tt>; you’re filling in a value for one of <tt class="docutils literal"><span class="pre">f()</span></tt>‘s parameters. This is called “partial function application”.</p> <p>The constructor for <tt class="docutils literal"><span class="pre">partial</span></tt> takes the arguments <tt class="docutils literal"><span class="pre">(function,</span> <span class="pre">arg1,</span> <span class="pre">arg2,</span> <span class="pre">...</span> <span class="pre">kwarg1=value1,</span> <span class="pre">kwarg2=value2)</span></tt>. The resulting object is callable, so you can just call it to invoke <tt class="docutils literal"><span class="pre">function</span></tt> with the filled-in arguments.</p> <p>Here’s a small but realistic example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">functools</span> <span class="k">def</span> <span class="nf">log</span> <span class="p">(</span><span class="n">message</span><span class="p">,</span> <span class="n">subsystem</span><span class="p">):</span> <span class="s">"Write the contents of 'message' to the specified subsystem."</span> <span class="k">print</span> <span class="s">'</span><span class="si">%s</span><span class="s">: </span><span class="si">%s</span><span class="s">'</span> <span class="o">%</span> <span class="p">(</span><span class="n">subsystem</span><span class="p">,</span> <span class="n">message</span><span class="p">)</span> <span class="o">...</span> <span class="n">server_log</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="n">log</span><span class="p">,</span> <span class="n">subsystem</span><span class="o">=</span><span class="s">'server'</span><span class="p">)</span> <span class="n">server_log</span><span class="p">(</span><span class="s">'Unable to open socket'</span><span class="p">)</span> </pre></div> </div> <div class="section" id="the-operator-module"> <h3>The operator module<a class="headerlink" href="#the-operator-module" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><tt class="xref py py-mod docutils literal"><span class="pre">operator</span></tt></a> module was mentioned earlier. It contains a set of functions corresponding to Python’s operators. These functions are often useful in functional-style code because they save you from writing trivial functions that perform a single operation.</p> <p>Some of the functions in this module are:</p> <ul class="simple"> <li>Math operations: <tt class="docutils literal"><span class="pre">add()</span></tt>, <tt class="docutils literal"><span class="pre">sub()</span></tt>, <tt class="docutils literal"><span class="pre">mul()</span></tt>, <tt class="docutils literal"><span class="pre">div()</span></tt>, <tt class="docutils literal"><span class="pre">floordiv()</span></tt>, <tt class="docutils literal"><span class="pre">abs()</span></tt>, ...</li> <li>Logical operations: <tt class="docutils literal"><span class="pre">not_()</span></tt>, <tt class="docutils literal"><span class="pre">truth()</span></tt>.</li> <li>Bitwise operations: <tt class="docutils literal"><span class="pre">and_()</span></tt>, <tt class="docutils literal"><span class="pre">or_()</span></tt>, <tt class="docutils literal"><span class="pre">invert()</span></tt>.</li> <li>Comparisons: <tt class="docutils literal"><span class="pre">eq()</span></tt>, <tt class="docutils literal"><span class="pre">ne()</span></tt>, <tt class="docutils literal"><span class="pre">lt()</span></tt>, <tt class="docutils literal"><span class="pre">le()</span></tt>, <tt class="docutils literal"><span class="pre">gt()</span></tt>, and <tt class="docutils literal"><span class="pre">ge()</span></tt>.</li> <li>Object identity: <tt class="docutils literal"><span class="pre">is_()</span></tt>, <tt class="docutils literal"><span class="pre">is_not()</span></tt>.</li> </ul> <p>Consult the operator module’s documentation for a complete list.</p> </div> </div> <div class="section" id="revision-history-and-acknowledgements"> <h2>Revision History and Acknowledgements<a class="headerlink" href="#revision-history-and-acknowledgements" title="Permalink to this headline">¶</a></h2> <p>The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this article: Ian Bicking, Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro Lameiro, Jussi Salmela, Collin Winter, Blake Winton.</p> <p>Version 0.1: posted June 30 2006.</p> <p>Version 0.11: posted July 1 2006. Typo fixes.</p> <p>Version 0.2: posted July 10 2006. Merged genexp and listcomp sections into one. Typo fixes.</p> <p>Version 0.21: Added more references suggested on the tutor mailing list.</p> <p>Version 0.30: Adds a section on the <tt class="docutils literal"><span class="pre">functional</span></tt> module written by Collin Winter; adds short section on the operator module; a few other edits.</p> </div> <div class="section" id="references"> <h2>References<a class="headerlink" href="#references" title="Permalink to this headline">¶</a></h2> <div class="section" id="general"> <h3>General<a class="headerlink" href="#general" title="Permalink to this headline">¶</a></h3> <p><strong>Structure and Interpretation of Computer Programs</strong>, by Harold Abelson and Gerald Jay Sussman with Julie Sussman. Full text at <a class="reference external" href="http://mitpress.mit.edu/sicp/">http://mitpress.mit.edu/sicp/</a>. In this classic textbook of computer science, chapters 2 and 3 discuss the use of sequences and streams to organize the data flow inside a program. The book uses Scheme for its examples, but many of the design approaches described in these chapters are applicable to functional-style Python code.</p> <p><a class="reference external" href="http://www.defmacro.org/ramblings/fp.html">http://www.defmacro.org/ramblings/fp.html</a>: A general introduction to functional programming that uses Java examples and has a lengthy historical introduction.</p> <p><a class="reference external" href="http://en.wikipedia.org/wiki/Functional_programming">http://en.wikipedia.org/wiki/Functional_programming</a>: General Wikipedia entry describing functional programming.</p> <p><a class="reference external" href="http://en.wikipedia.org/wiki/Coroutine">http://en.wikipedia.org/wiki/Coroutine</a>: Entry for coroutines.</p> <p><a class="reference external" href="http://en.wikipedia.org/wiki/Currying">http://en.wikipedia.org/wiki/Currying</a>: Entry for the concept of currying.</p> </div> <div class="section" id="python-specific"> <h3>Python-specific<a class="headerlink" href="#python-specific" title="Permalink to this headline">¶</a></h3> <p><a class="reference external" href="http://gnosis.cx/TPiP/">http://gnosis.cx/TPiP/</a>: The first chapter of David Mertz’s book <cite>Text Processing in Python</cite> discusses functional programming for text processing, in the section titled “Utilizing Higher-Order Functions in Text Processing”.</p> <p>Mertz also wrote a 3-part series of articles on functional programming for IBM’s DeveloperWorks site; see</p> <p><a class="reference external" href="http://www.ibm.com/developerworks/linux/library/l-prog/index.html">part 1</a>, <a class="reference external" href="http://www.ibm.com/developerworks/linux/library/l-prog2/index.html">part 2</a>, and <a class="reference external" href="http://www.ibm.com/developerworks/linux/library/l-prog3/index.html">part 3</a>,</p> </div> <div class="section" id="python-documentation"> <h3>Python documentation<a class="headerlink" href="#python-documentation" title="Permalink to this headline">¶</a></h3> <p>Documentation for the <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><tt class="xref py py-mod docutils literal"><span class="pre">itertools</span></tt></a> module.</p> <p>Documentation for the <a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><tt class="xref py py-mod docutils literal"><span class="pre">operator</span></tt></a> module.</p> <p><span class="target" id="index-0"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0289"><strong>PEP 289</strong></a>: “Generator Expressions”</p> <p><span class="target" id="index-1"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0342"><strong>PEP 342</strong></a>: “Coroutines via Enhanced Generators” describes the new generator features in Python 2.5.</p> </div> </div> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h3><a href="../contents.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">Functional Programming HOWTO</a><ul> <li><a class="reference internal" href="#introduction">Introduction</a><ul> <li><a class="reference internal" href="#formal-provability">Formal provability</a></li> <li><a class="reference internal" href="#modularity">Modularity</a></li> <li><a class="reference internal" href="#ease-of-debugging-and-testing">Ease of debugging and testing</a></li> <li><a class="reference internal" href="#composability">Composability</a></li> </ul> </li> <li><a class="reference internal" href="#iterators">Iterators</a><ul> <li><a class="reference internal" href="#data-types-that-support-iterators">Data Types That Support Iterators</a></li> </ul> </li> <li><a class="reference internal" href="#generator-expressions-and-list-comprehensions">Generator expressions and list comprehensions</a></li> <li><a class="reference internal" href="#generators">Generators</a><ul> <li><a class="reference internal" href="#passing-values-into-a-generator">Passing values into a generator</a></li> </ul> </li> <li><a class="reference internal" href="#built-in-functions">Built-in functions</a></li> <li><a class="reference internal" href="#small-functions-and-the-lambda-expression">Small functions and the lambda expression</a></li> <li><a class="reference internal" href="#the-itertools-module">The itertools module</a><ul> <li><a class="reference internal" href="#creating-new-iterators">Creating new iterators</a></li> <li><a class="reference internal" href="#calling-functions-on-elements">Calling functions on elements</a></li> <li><a class="reference internal" href="#selecting-elements">Selecting elements</a></li> <li><a class="reference internal" href="#grouping-elements">Grouping elements</a></li> </ul> </li> <li><a class="reference internal" href="#the-functools-module">The functools module</a><ul> <li><a class="reference internal" href="#the-operator-module">The operator module</a></li> </ul> </li> <li><a class="reference internal" href="#revision-history-and-acknowledgements">Revision History and Acknowledgements</a></li> <li><a class="reference internal" href="#references">References</a><ul> <li><a class="reference internal" href="#general">General</a></li> <li><a class="reference internal" href="#python-specific">Python-specific</a></li> <li><a class="reference internal" href="#python-documentation">Python documentation</a></li> </ul> </li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="doanddont.html" title="previous chapter">Idioms and Anti-Idioms in Python</a></p> <h4>Next topic</h4> <p class="topless"><a href="logging.html" title="next chapter">Logging HOWTO</a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a Bug</a></li> <li><a href="../_sources/howto/functional.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="logging.html" title="Logging HOWTO" >next</a> |</li> <li class="right" > <a href="doanddont.html" title="Idioms and Anti-Idioms in Python" >previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="http://www.python.org/">Python</a> »</li> <li> <a href="../index.html">Python 2.7.5 documentation</a> » </li> <li><a href="index.html" >Python HOWTOs</a> »</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation. <br /> The Python Software Foundation is a non-profit corporation. <a href="http://www.python.org/psf/donations/">Please donate.</a> <br /> Last updated on Jul 03, 2019. <a href="../bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3. </div> </body> </html>