[ Avaa Bypassed ]




Upload:

Command:

hmhc3928@3.135.218.67: ~ $

<!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>8.3. collections — High-performance container datatypes &mdash; 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="8. Data Types" href="datatypes.html" />
    <link rel="next" title="8.4. heapq — Heap queue algorithm" href="heapq.html" />
    <link rel="prev" title="8.2. calendar — General calendar-related functions" href="calendar.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="heapq.html" title="8.4. heapq — Heap queue algorithm"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="calendar.html" title="8.2. calendar — General calendar-related functions"
             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> &raquo;</li>
        <li>
          <a href="../index.html">Python 2.7.5 documentation</a> &raquo;
        </li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="datatypes.html" accesskey="U">8. Data Types</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="module-collections">
<span id="collections-high-performance-container-datatypes"></span><h1>8.3. <a class="reference internal" href="#module-collections" title="collections: High-performance datatypes"><tt class="xref py py-mod docutils literal"><span class="pre">collections</span></tt></a> &#8212; High-performance container datatypes<a class="headerlink" href="#module-collections" title="Permalink to this headline">¶</a></h1>
<p class="versionadded">
<span class="versionmodified">New in version 2.4.</span></p>
<p><strong>Source code:</strong> <a class="reference external" href="http://hg.python.org/cpython/file/2.7/Lib/collections.py">Lib/collections.py</a> and <a class="reference external" href="http://hg.python.org/cpython/file/2.7/Lib/_abcoll.py">Lib/_abcoll.py</a></p>
<hr class="docutils" />
<p>This module implements specialized container datatypes providing alternatives to
Python&#8217;s general purpose built-in containers, <a class="reference internal" href="stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a>, <a class="reference internal" href="functions.html#list" title="list"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a>,
<a class="reference internal" href="stdtypes.html#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a>, and <a class="reference internal" href="functions.html#tuple" title="tuple"><tt class="xref py py-class docutils literal"><span class="pre">tuple</span></tt></a>.</p>
<table border="1" class="docutils">
<colgroup>
<col width="18%" />
<col width="59%" />
<col width="23%" />
</colgroup>
<tbody valign="top">
<tr class="row-odd"><td><a class="reference internal" href="#collections.namedtuple" title="collections.namedtuple"><tt class="xref py py-func docutils literal"><span class="pre">namedtuple()</span></tt></a></td>
<td>factory function for creating tuple subclasses with named fields</td>
<td><p class="first last versionadded">
<span class="versionmodified">New in version 2.6.</span></p>
</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.deque" title="collections.deque"><tt class="xref py py-class docutils literal"><span class="pre">deque</span></tt></a></td>
<td>list-like container with fast appends and pops on either end</td>
<td><p class="first last versionadded">
<span class="versionmodified">New in version 2.4.</span></p>
</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.Counter" title="collections.Counter"><tt class="xref py py-class docutils literal"><span class="pre">Counter</span></tt></a></td>
<td>dict subclass for counting hashable objects</td>
<td><p class="first last versionadded">
<span class="versionmodified">New in version 2.7.</span></p>
</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><tt class="xref py py-class docutils literal"><span class="pre">OrderedDict</span></tt></a></td>
<td>dict subclass that remembers the order entries were added</td>
<td><p class="first last versionadded">
<span class="versionmodified">New in version 2.7.</span></p>
</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><tt class="xref py py-class docutils literal"><span class="pre">defaultdict</span></tt></a></td>
<td>dict subclass that calls a factory function to supply missing values</td>
<td><p class="first last versionadded">
<span class="versionmodified">New in version 2.5.</span></p>
</td>
</tr>
</tbody>
</table>
<p>In addition to the concrete container classes, the collections module provides
<a class="reference internal" href="#collections-abstract-base-classes"><em>abstract base classes</em></a> that can be
used to test whether a class provides a particular interface, for example,
whether it is hashable or a mapping.</p>
<div class="section" id="counter-objects">
<h2>8.3.1. <a class="reference internal" href="#collections.Counter" title="collections.Counter"><tt class="xref py py-class docutils literal"><span class="pre">Counter</span></tt></a> objects<a class="headerlink" href="#counter-objects" title="Permalink to this headline">¶</a></h2>
<p>A counter tool is provided to support convenient and rapid tallies.
For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="c"># Tally occurrences of words in a list</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cnt</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="p">[</span><span class="s">&#39;red&#39;</span><span class="p">,</span> <span class="s">&#39;blue&#39;</span><span class="p">,</span> <span class="s">&#39;red&#39;</span><span class="p">,</span> <span class="s">&#39;green&#39;</span><span class="p">,</span> <span class="s">&#39;blue&#39;</span><span class="p">,</span> <span class="s">&#39;blue&#39;</span><span class="p">]:</span>
<span class="gp">... </span>    <span class="n">cnt</span><span class="p">[</span><span class="n">word</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cnt</span>
<span class="go">Counter({&#39;blue&#39;: 3, &#39;red&#39;: 2, &#39;green&#39;: 1})</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c"># Find the ten most common words in Hamlet</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">words</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s">r&#39;\w+&#39;</span><span class="p">,</span> <span class="nb">open</span><span class="p">(</span><span class="s">&#39;hamlet.txt&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span><span class="o">.</span><span class="n">lower</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Counter</span><span class="p">(</span><span class="n">words</span><span class="p">)</span><span class="o">.</span><span class="n">most_common</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="go">[(&#39;the&#39;, 1143), (&#39;and&#39;, 966), (&#39;to&#39;, 762), (&#39;of&#39;, 669), (&#39;i&#39;, 631),</span>
<span class="go"> (&#39;you&#39;, 554),  (&#39;a&#39;, 546), (&#39;my&#39;, 514), (&#39;hamlet&#39;, 471), (&#39;in&#39;, 451)]</span>
</pre></div>
</div>
<dl class="class">
<dt id="collections.Counter">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">Counter</tt><big>(</big><span class="optional">[</span><em>iterable-or-mapping</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#collections.Counter" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#collections.Counter" title="collections.Counter"><tt class="xref py py-class docutils literal"><span class="pre">Counter</span></tt></a> is a <a class="reference internal" href="stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> subclass for counting hashable objects.
It is an unordered collection where elements are stored as dictionary keys
and their counts are stored as dictionary values.  Counts are allowed to be
any integer value including zero or negative counts.  The <a class="reference internal" href="#collections.Counter" title="collections.Counter"><tt class="xref py py-class docutils literal"><span class="pre">Counter</span></tt></a>
class is similar to bags or multisets in other languages.</p>
<p>Elements are counted from an <em>iterable</em> or initialized from another
<em>mapping</em> (or counter):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span>                           <span class="c"># a new, empty counter</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="s">&#39;gallahad&#39;</span><span class="p">)</span>                 <span class="c"># a new counter from an iterable</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">({</span><span class="s">&#39;red&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span> <span class="s">&#39;blue&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">})</span>      <span class="c"># a new counter from a mapping</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">cats</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">dogs</span><span class="o">=</span><span class="mi">8</span><span class="p">)</span>             <span class="c"># a new counter from keyword args</span>
</pre></div>
</div>
<p>Counter objects have a dictionary interface except that they return a zero
count for missing items instead of raising a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">([</span><span class="s">&#39;eggs&#39;</span><span class="p">,</span> <span class="s">&#39;ham&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s">&#39;bacon&#39;</span><span class="p">]</span>                              <span class="c"># count of a missing element is zero</span>
<span class="go">0</span>
</pre></div>
</div>
<p>Setting a count to zero does not remove an element from a counter.
Use <tt class="docutils literal"><span class="pre">del</span></tt> to remove it entirely:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s">&#39;sausage&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span>                        <span class="c"># counter entry with a zero count</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">c</span><span class="p">[</span><span class="s">&#39;sausage&#39;</span><span class="p">]</span>                        <span class="c"># del actually removes the entry</span>
</pre></div>
</div>
<p class="versionadded">
<span class="versionmodified">New in version 2.7.</span></p>
<p>Counter objects support three methods beyond those available for all
dictionaries:</p>
<dl class="method">
<dt id="collections.Counter.elements">
<tt class="descname">elements</tt><big>(</big><big>)</big><a class="headerlink" href="#collections.Counter.elements" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator over elements repeating each as many times as its
count.  Elements are returned in arbitrary order.  If an element&#8217;s count
is less than one, <a class="reference internal" href="#collections.Counter.elements" title="collections.Counter.elements"><tt class="xref py py-meth docutils literal"><span class="pre">elements()</span></tt></a> will ignore it.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">d</span><span class="o">=-</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">elements</span><span class="p">())</span>
<span class="go">[&#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;b&#39;, &#39;b&#39;]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.Counter.most_common">
<tt class="descname">most_common</tt><big>(</big><span class="optional">[</span><em>n</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#collections.Counter.most_common" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the <em>n</em> most common elements and their counts from the
most common to the least.  If <em>n</em> is not specified, <a class="reference internal" href="#collections.Counter.most_common" title="collections.Counter.most_common"><tt class="xref py py-func docutils literal"><span class="pre">most_common()</span></tt></a>
returns <em>all</em> elements in the counter.  Elements with equal counts are
ordered arbitrarily:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Counter</span><span class="p">(</span><span class="s">&#39;abracadabra&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">most_common</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="go">[(&#39;a&#39;, 5), (&#39;r&#39;, 2), (&#39;b&#39;, 2)]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.Counter.subtract">
<tt class="descname">subtract</tt><big>(</big><span class="optional">[</span><em>iterable-or-mapping</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#collections.Counter.subtract" title="Permalink to this definition">¶</a></dt>
<dd><p>Elements are subtracted from an <em>iterable</em> or from another <em>mapping</em>
(or counter).  Like <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><tt class="xref py py-meth docutils literal"><span class="pre">dict.update()</span></tt></a> but subtracts counts instead
of replacing them.  Both inputs and outputs may be zero or negative.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">d</span><span class="o">=-</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">d</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">subtract</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span>
<span class="go">Counter({&#39;a&#39;: 3, &#39;b&#39;: 0, &#39;c&#39;: -3, &#39;d&#39;: -6})</span>
</pre></div>
</div>
</dd></dl>

<p>The usual dictionary methods are available for <a class="reference internal" href="#collections.Counter" title="collections.Counter"><tt class="xref py py-class docutils literal"><span class="pre">Counter</span></tt></a> objects
except for two which work differently for counters.</p>
<dl class="method">
<dt id="collections.Counter.fromkeys">
<tt class="descname">fromkeys</tt><big>(</big><em>iterable</em><big>)</big><a class="headerlink" href="#collections.Counter.fromkeys" title="Permalink to this definition">¶</a></dt>
<dd><p>This class method is not implemented for <a class="reference internal" href="#collections.Counter" title="collections.Counter"><tt class="xref py py-class docutils literal"><span class="pre">Counter</span></tt></a> objects.</p>
</dd></dl>

<dl class="method">
<dt id="collections.Counter.update">
<tt class="descname">update</tt><big>(</big><span class="optional">[</span><em>iterable-or-mapping</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#collections.Counter.update" title="Permalink to this definition">¶</a></dt>
<dd><p>Elements are counted from an <em>iterable</em> or added-in from another
<em>mapping</em> (or counter).  Like <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><tt class="xref py py-meth docutils literal"><span class="pre">dict.update()</span></tt></a> but adds counts
instead of replacing them.  Also, the <em>iterable</em> is expected to be a
sequence of elements, not a sequence of <tt class="docutils literal"><span class="pre">(key,</span> <span class="pre">value)</span></tt> pairs.</p>
</dd></dl>

</dd></dl>

<p>Common patterns for working with <a class="reference internal" href="#collections.Counter" title="collections.Counter"><tt class="xref py py-class docutils literal"><span class="pre">Counter</span></tt></a> objects:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nb">sum</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">values</span><span class="p">())</span>                 <span class="c"># total of all counts</span>
<span class="n">c</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>                       <span class="c"># reset all counts</span>
<span class="nb">list</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                         <span class="c"># list unique elements</span>
<span class="nb">set</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                          <span class="c"># convert to a set</span>
<span class="nb">dict</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                         <span class="c"># convert to a regular dictionary</span>
<span class="n">c</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>                       <span class="c"># convert to a list of (elem, cnt) pairs</span>
<span class="n">Counter</span><span class="p">(</span><span class="nb">dict</span><span class="p">(</span><span class="n">list_of_pairs</span><span class="p">))</span>    <span class="c"># convert from a list of (elem, cnt) pairs</span>
<span class="n">c</span><span class="o">.</span><span class="n">most_common</span><span class="p">()[:</span><span class="o">-</span><span class="n">n</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>         <span class="c"># n least common elements</span>
<span class="n">c</span> <span class="o">+=</span> <span class="n">Counter</span><span class="p">()</span>                  <span class="c"># remove zero and negative counts</span>
</pre></div>
</div>
<p>Several mathematical operations are provided for combining <a class="reference internal" href="#collections.Counter" title="collections.Counter"><tt class="xref py py-class docutils literal"><span class="pre">Counter</span></tt></a>
objects to produce multisets (counters that have counts greater than zero).
Addition and subtraction combine counters by adding or subtracting the counts
of corresponding elements.  Intersection and union return the minimum and
maximum of corresponding counts.  Each operation can accept inputs with signed
counts, but the output will exclude results with counts of zero or less.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">+</span> <span class="n">d</span>                       <span class="c"># add two counters together:  c[x] + d[x]</span>
<span class="go">Counter({&#39;a&#39;: 4, &#39;b&#39;: 3})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">-</span> <span class="n">d</span>                       <span class="c"># subtract (keeping only positive counts)</span>
<span class="go">Counter({&#39;a&#39;: 2})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">&amp;</span> <span class="n">d</span>                       <span class="c"># intersection:  min(c[x], d[x])</span>
<span class="go">Counter({&#39;a&#39;: 1, &#39;b&#39;: 1})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">|</span> <span class="n">d</span>                       <span class="c"># union:  max(c[x], d[x])</span>
<span class="go">Counter({&#39;a&#39;: 3, &#39;b&#39;: 2})</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Counters were primarily designed to work with positive integers to represent
running counts; however, care was taken to not unnecessarily preclude use
cases needing other types or negative values.  To help with those use cases,
this section documents the minimum range and type restrictions.</p>
<ul class="last simple">
<li>The <a class="reference internal" href="#collections.Counter" title="collections.Counter"><tt class="xref py py-class docutils literal"><span class="pre">Counter</span></tt></a> class itself is a dictionary subclass with no
restrictions on its keys and values.  The values are intended to be numbers
representing counts, but you <em>could</em> store anything in the value field.</li>
<li>The <tt class="xref py py-meth docutils literal"><span class="pre">most_common()</span></tt> method requires only that the values be orderable.</li>
<li>For in-place operations such as <tt class="docutils literal"><span class="pre">c[key]</span> <span class="pre">+=</span> <span class="pre">1</span></tt>, the value type need only
support addition and subtraction.  So fractions, floats, and decimals would
work and negative values are supported.  The same is also true for
<tt class="xref py py-meth docutils literal"><span class="pre">update()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">subtract()</span></tt> which allow negative and zero values
for both inputs and outputs.</li>
<li>The multiset methods are designed only for use cases with positive values.
The inputs may be negative or zero, but only outputs with positive values
are created.  There are no type restrictions, but the value type needs to
support addition, subtraction, and comparison.</li>
<li>The <tt class="xref py py-meth docutils literal"><span class="pre">elements()</span></tt> method requires integer counts.  It ignores zero and
negative counts.</li>
</ul>
</div>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<ul class="last">
<li><p class="first"><a class="reference external" href="http://code.activestate.com/recipes/576611/">Counter class</a>
adapted for Python 2.5 and an early <a class="reference external" href="http://code.activestate.com/recipes/259174/">Bag recipe</a> for Python 2.4.</p>
</li>
<li><p class="first"><a class="reference external" href="http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html">Bag class</a>
in Smalltalk.</p>
</li>
<li><p class="first">Wikipedia entry for <a class="reference external" href="http://en.wikipedia.org/wiki/Multiset">Multisets</a>.</p>
</li>
<li><p class="first"><a class="reference external" href="http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm">C++ multisets</a>
tutorial with examples.</p>
</li>
<li><p class="first">For mathematical operations on multisets and their use cases, see
<em>Knuth, Donald. The Art of Computer Programming Volume II,
Section 4.6.3, Exercise 19</em>.</p>
</li>
<li><p class="first">To enumerate all distinct multisets of a given size over a given set of
elements, see <a class="reference internal" href="itertools.html#itertools.combinations_with_replacement" title="itertools.combinations_with_replacement"><tt class="xref py py-func docutils literal"><span class="pre">itertools.combinations_with_replacement()</span></tt></a>.</p>
<blockquote>
<div><p>map(Counter, combinations_with_replacement(&#8216;ABC&#8217;, 2)) &#8211;&gt; AA AB AC BB BC CC</p>
</div></blockquote>
</li>
</ul>
</div>
</div>
<div class="section" id="deque-objects">
<h2>8.3.2. <a class="reference internal" href="#collections.deque" title="collections.deque"><tt class="xref py py-class docutils literal"><span class="pre">deque</span></tt></a> objects<a class="headerlink" href="#deque-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="collections.deque">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">deque</tt><big>(</big><span class="optional">[</span><em>iterable</em><span class="optional">[</span>, <em>maxlen</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#collections.deque" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new deque object initialized left-to-right (using <a class="reference internal" href="#collections.deque.append" title="collections.deque.append"><tt class="xref py py-meth docutils literal"><span class="pre">append()</span></tt></a>) with
data from <em>iterable</em>.  If <em>iterable</em> is not specified, the new deque is empty.</p>
<p>Deques are a generalization of stacks and queues (the name is pronounced &#8220;deck&#8221;
and is short for &#8220;double-ended queue&#8221;).  Deques support thread-safe, memory
efficient appends and pops from either side of the deque with approximately the
same O(1) performance in either direction.</p>
<p>Though <a class="reference internal" href="functions.html#list" title="list"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a> objects support similar operations, they are optimized for
fast fixed-length operations and incur O(n) memory movement costs for
<tt class="docutils literal"><span class="pre">pop(0)</span></tt> and <tt class="docutils literal"><span class="pre">insert(0,</span> <span class="pre">v)</span></tt> operations which change both the size and
position of the underlying data representation.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.4.</span></p>
<p>If <em>maxlen</em> is not specified or is <em>None</em>, deques may grow to an
arbitrary length.  Otherwise, the deque is bounded to the specified maximum
length.  Once a bounded length deque is full, when new items are added, a
corresponding number of items are discarded from the opposite end.  Bounded
length deques provide functionality similar to the <tt class="docutils literal"><span class="pre">tail</span></tt> filter in
Unix. They are also useful for tracking transactions and other pools of data
where only the most recent activity is of interest.</p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 2.6: </span>Added <em>maxlen</em> parameter.</p>
<p>Deque objects support the following methods:</p>
<dl class="method">
<dt id="collections.deque.append">
<tt class="descname">append</tt><big>(</big><em>x</em><big>)</big><a class="headerlink" href="#collections.deque.append" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>x</em> to the right side of the deque.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.appendleft">
<tt class="descname">appendleft</tt><big>(</big><em>x</em><big>)</big><a class="headerlink" href="#collections.deque.appendleft" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>x</em> to the left side of the deque.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.clear">
<tt class="descname">clear</tt><big>(</big><big>)</big><a class="headerlink" href="#collections.deque.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove all elements from the deque leaving it with length 0.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.count">
<tt class="descname">count</tt><big>(</big><em>x</em><big>)</big><a class="headerlink" href="#collections.deque.count" title="Permalink to this definition">¶</a></dt>
<dd><p>Count the number of deque elements equal to <em>x</em>.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.7.</span></p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.extend">
<tt class="descname">extend</tt><big>(</big><em>iterable</em><big>)</big><a class="headerlink" href="#collections.deque.extend" title="Permalink to this definition">¶</a></dt>
<dd><p>Extend the right side of the deque by appending elements from the iterable
argument.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.extendleft">
<tt class="descname">extendleft</tt><big>(</big><em>iterable</em><big>)</big><a class="headerlink" href="#collections.deque.extendleft" title="Permalink to this definition">¶</a></dt>
<dd><p>Extend the left side of the deque by appending elements from <em>iterable</em>.
Note, the series of left appends results in reversing the order of
elements in the iterable argument.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.pop">
<tt class="descname">pop</tt><big>(</big><big>)</big><a class="headerlink" href="#collections.deque.pop" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove and return an element from the right side of the deque. If no
elements are present, raises an <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><tt class="xref py py-exc docutils literal"><span class="pre">IndexError</span></tt></a>.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.popleft">
<tt class="descname">popleft</tt><big>(</big><big>)</big><a class="headerlink" href="#collections.deque.popleft" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove and return an element from the left side of the deque. If no
elements are present, raises an <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><tt class="xref py py-exc docutils literal"><span class="pre">IndexError</span></tt></a>.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.remove">
<tt class="descname">remove</tt><big>(</big><em>value</em><big>)</big><a class="headerlink" href="#collections.deque.remove" title="Permalink to this definition">¶</a></dt>
<dd><p>Removed the first occurrence of <em>value</em>.  If not found, raises a
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a>.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.5.</span></p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.reverse">
<tt class="descname">reverse</tt><big>(</big><big>)</big><a class="headerlink" href="#collections.deque.reverse" title="Permalink to this definition">¶</a></dt>
<dd><p>Reverse the elements of the deque in-place and then return <tt class="docutils literal"><span class="pre">None</span></tt>.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.7.</span></p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.rotate">
<tt class="descname">rotate</tt><big>(</big><em>n</em><big>)</big><a class="headerlink" href="#collections.deque.rotate" title="Permalink to this definition">¶</a></dt>
<dd><p>Rotate the deque <em>n</em> steps to the right.  If <em>n</em> is negative, rotate to
the left.  Rotating one step to the right is equivalent to:
<tt class="docutils literal"><span class="pre">d.appendleft(d.pop())</span></tt>.</p>
</dd></dl>

<p>Deque objects also provide one read-only attribute:</p>
<dl class="attribute">
<dt id="collections.deque.maxlen">
<tt class="descname">maxlen</tt><a class="headerlink" href="#collections.deque.maxlen" title="Permalink to this definition">¶</a></dt>
<dd><p>Maximum size of a deque or <em>None</em> if unbounded.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.7.</span></p>
</dd></dl>

</dd></dl>

<p>In addition to the above, deques support iteration, pickling, <tt class="docutils literal"><span class="pre">len(d)</span></tt>,
<tt class="docutils literal"><span class="pre">reversed(d)</span></tt>, <tt class="docutils literal"><span class="pre">copy.copy(d)</span></tt>, <tt class="docutils literal"><span class="pre">copy.deepcopy(d)</span></tt>, membership testing with
the <a class="reference internal" href="../reference/expressions.html#in"><tt class="xref std std-keyword docutils literal"><span class="pre">in</span></tt></a> operator, and subscript references such as <tt class="docutils literal"><span class="pre">d[-1]</span></tt>.  Indexed
access is O(1) at both ends but slows to O(n) in the middle.  For fast random
access, use lists instead.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="s">&#39;ghi&#39;</span><span class="p">)</span>                 <span class="c"># make a new deque with three items</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">d</span><span class="p">:</span>                   <span class="c"># iterate over the deque&#39;s elements</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="n">elem</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
<span class="go">G</span>
<span class="go">H</span>
<span class="go">I</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s">&#39;j&#39;</span><span class="p">)</span>                    <span class="c"># add a new entry to the right side</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">appendleft</span><span class="p">(</span><span class="s">&#39;f&#39;</span><span class="p">)</span>                <span class="c"># add a new entry to the left side</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>                                <span class="c"># show the representation of the deque</span>
<span class="go">deque([&#39;f&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>                          <span class="c"># return and remove the rightmost item</span>
<span class="go">&#39;j&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>                      <span class="c"># return and remove the leftmost item</span>
<span class="go">&#39;f&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>                          <span class="c"># list the contents of the deque</span>
<span class="go">[&#39;g&#39;, &#39;h&#39;, &#39;i&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>                             <span class="c"># peek at leftmost item</span>
<span class="go">&#39;g&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>                            <span class="c"># peek at rightmost item</span>
<span class="go">&#39;i&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="n">d</span><span class="p">))</span>                <span class="c"># list the contents of a deque in reverse</span>
<span class="go">[&#39;i&#39;, &#39;h&#39;, &#39;g&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;h&#39;</span> <span class="ow">in</span> <span class="n">d</span>                         <span class="c"># search the deque</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="s">&#39;jkl&#39;</span><span class="p">)</span>                  <span class="c"># add multiple elements at once</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>                      <span class="c"># right rotation</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;l&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>                     <span class="c"># left rotation</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">deque</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="n">d</span><span class="p">))</span>               <span class="c"># make a new deque in reverse order</span>
<span class="go">deque([&#39;l&#39;, &#39;k&#39;, &#39;j&#39;, &#39;i&#39;, &#39;h&#39;, &#39;g&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>                        <span class="c"># empty the deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>                          <span class="c"># cannot pop from an empty deque</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;pyshell#6&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">-toplevel-</span>
    <span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="gr">IndexError</span>: <span class="n">pop from an empty deque</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">extendleft</span><span class="p">(</span><span class="s">&#39;abc&#39;</span><span class="p">)</span>              <span class="c"># extendleft() reverses the input order</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;c&#39;, &#39;b&#39;, &#39;a&#39;])</span>
</pre></div>
</div>
<div class="section" id="deque-recipes">
<h3>8.3.2.1. <a class="reference internal" href="#collections.deque" title="collections.deque"><tt class="xref py py-class docutils literal"><span class="pre">deque</span></tt></a> Recipes<a class="headerlink" href="#deque-recipes" title="Permalink to this headline">¶</a></h3>
<p>This section shows various approaches to working with deques.</p>
<p>Bounded length deques provide functionality similar to the <tt class="docutils literal"><span class="pre">tail</span></tt> filter
in Unix:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">tail</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="mi">10</span><span class="p">):</span>
    <span class="s">&#39;Return the last n lines of a file&#39;</span>
    <span class="k">return</span> <span class="n">deque</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">),</span> <span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
<p>Another approach to using deques is to maintain a sequence of recently
added elements by appending to the right and popping to the left:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">moving_average</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="mi">3</span><span class="p">):</span>
    <span class="c"># moving_average([40, 30, 50, 46, 39, 44]) --&gt; 40.0 42.0 45.0 43.0</span>
    <span class="c"># http://en.wikipedia.org/wiki/Moving_average</span>
    <span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">islice</span><span class="p">(</span><span class="n">it</span><span class="p">,</span> <span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">))</span>
    <span class="n">d</span><span class="o">.</span><span class="n">appendleft</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
    <span class="n">s</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">it</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">+=</span> <span class="n">elem</span> <span class="o">-</span> <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
        <span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">elem</span><span class="p">)</span>
        <span class="k">yield</span> <span class="n">s</span> <span class="o">/</span> <span class="nb">float</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
<p>The <tt class="xref py py-meth docutils literal"><span class="pre">rotate()</span></tt> method provides a way to implement <a class="reference internal" href="#collections.deque" title="collections.deque"><tt class="xref py py-class docutils literal"><span class="pre">deque</span></tt></a> slicing and
deletion.  For example, a pure Python implementation of <tt class="docutils literal"><span class="pre">del</span> <span class="pre">d[n]</span></tt> relies on
the <tt class="xref py py-meth docutils literal"><span class="pre">rotate()</span></tt> method to position elements to be popped:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">delete_nth</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
    <span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="o">-</span><span class="n">n</span><span class="p">)</span>
    <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
    <span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
<p>To implement <a class="reference internal" href="#collections.deque" title="collections.deque"><tt class="xref py py-class docutils literal"><span class="pre">deque</span></tt></a> slicing, use a similar approach applying
<tt class="xref py py-meth docutils literal"><span class="pre">rotate()</span></tt> to bring a target element to the left side of the deque. Remove
old entries with <tt class="xref py py-meth docutils literal"><span class="pre">popleft()</span></tt>, add new entries with <tt class="xref py py-meth docutils literal"><span class="pre">extend()</span></tt>, and then
reverse the rotation.
With minor variations on that approach, it is easy to implement Forth style
stack manipulations such as <tt class="docutils literal"><span class="pre">dup</span></tt>, <tt class="docutils literal"><span class="pre">drop</span></tt>, <tt class="docutils literal"><span class="pre">swap</span></tt>, <tt class="docutils literal"><span class="pre">over</span></tt>, <tt class="docutils literal"><span class="pre">pick</span></tt>,
<tt class="docutils literal"><span class="pre">rot</span></tt>, and <tt class="docutils literal"><span class="pre">roll</span></tt>.</p>
</div>
</div>
<div class="section" id="defaultdict-objects">
<h2>8.3.3. <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><tt class="xref py py-class docutils literal"><span class="pre">defaultdict</span></tt></a> objects<a class="headerlink" href="#defaultdict-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="collections.defaultdict">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">defaultdict</tt><big>(</big><span class="optional">[</span><em>default_factory</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#collections.defaultdict" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new dictionary-like object.  <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><tt class="xref py py-class docutils literal"><span class="pre">defaultdict</span></tt></a> is a subclass of the
built-in <a class="reference internal" href="stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> class.  It overrides one method and adds one writable
instance variable.  The remaining functionality is the same as for the
<a class="reference internal" href="stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> class and is not documented here.</p>
<p>The first argument provides the initial value for the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><tt class="xref py py-attr docutils literal"><span class="pre">default_factory</span></tt></a>
attribute; it defaults to <tt class="docutils literal"><span class="pre">None</span></tt>. All remaining arguments are treated the same
as if they were passed to the <a class="reference internal" href="stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> constructor, including keyword
arguments.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.5.</span></p>
<p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><tt class="xref py py-class docutils literal"><span class="pre">defaultdict</span></tt></a> objects support the following method in addition to the
standard <a class="reference internal" href="stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> operations:</p>
<dl class="method">
<dt id="collections.defaultdict.__missing__">
<tt class="descname">__missing__</tt><big>(</big><em>key</em><big>)</big><a class="headerlink" href="#collections.defaultdict.__missing__" title="Permalink to this definition">¶</a></dt>
<dd><p>If the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><tt class="xref py py-attr docutils literal"><span class="pre">default_factory</span></tt></a> attribute is <tt class="docutils literal"><span class="pre">None</span></tt>, this raises a
<a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> exception with the <em>key</em> as argument.</p>
<p>If <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><tt class="xref py py-attr docutils literal"><span class="pre">default_factory</span></tt></a> is not <tt class="docutils literal"><span class="pre">None</span></tt>, it is called without arguments
to provide a default value for the given <em>key</em>, this value is inserted in
the dictionary for the <em>key</em>, and returned.</p>
<p>If calling <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><tt class="xref py py-attr docutils literal"><span class="pre">default_factory</span></tt></a> raises an exception this exception is
propagated unchanged.</p>
<p>This method is called by the <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a> method of the
<a class="reference internal" href="stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> class when the requested key is not found; whatever it
returns or raises is then returned or raised by <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>.</p>
<p>Note that <a class="reference internal" href="#collections.defaultdict.__missing__" title="collections.defaultdict.__missing__"><tt class="xref py py-meth docutils literal"><span class="pre">__missing__()</span></tt></a> is <em>not</em> called for any operations besides
<a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>. This means that <tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt> will, like normal
dictionaries, return <tt class="docutils literal"><span class="pre">None</span></tt> as a default rather than using
<a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><tt class="xref py py-attr docutils literal"><span class="pre">default_factory</span></tt></a>.</p>
</dd></dl>

<p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><tt class="xref py py-class docutils literal"><span class="pre">defaultdict</span></tt></a> objects support the following instance variable:</p>
<dl class="attribute">
<dt id="collections.defaultdict.default_factory">
<tt class="descname">default_factory</tt><a class="headerlink" href="#collections.defaultdict.default_factory" title="Permalink to this definition">¶</a></dt>
<dd><p>This attribute is used by the <a class="reference internal" href="#collections.defaultdict.__missing__" title="collections.defaultdict.__missing__"><tt class="xref py py-meth docutils literal"><span class="pre">__missing__()</span></tt></a> method; it is
initialized from the first argument to the constructor, if present, or to
<tt class="docutils literal"><span class="pre">None</span></tt>, if absent.</p>
</dd></dl>

</dd></dl>

<div class="section" id="defaultdict-examples">
<h3>8.3.3.1. <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><tt class="xref py py-class docutils literal"><span class="pre">defaultdict</span></tt></a> Examples<a class="headerlink" href="#defaultdict-examples" title="Permalink to this headline">¶</a></h3>
<p>Using <a class="reference internal" href="functions.html#list" title="list"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a> as the <tt class="xref py py-attr docutils literal"><span class="pre">default_factory</span></tt>, it is easy to group a
sequence of key-value pairs into a dictionary of lists:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&#39;yellow&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;yellow&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;red&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;blue&#39;, [2, 4]), (&#39;red&#39;, [1]), (&#39;yellow&#39;, [1, 3])]</span>
</pre></div>
</div>
<p>When each key is encountered for the first time, it is not already in the
mapping; so an entry is automatically created using the <tt class="xref py py-attr docutils literal"><span class="pre">default_factory</span></tt>
function which returns an empty <a class="reference internal" href="functions.html#list" title="list"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a>.  The <tt class="xref py py-meth docutils literal"><span class="pre">list.append()</span></tt>
operation then attaches the value to the new list.  When keys are encountered
again, the look-up proceeds normally (returning the list for that key) and the
<tt class="xref py py-meth docutils literal"><span class="pre">list.append()</span></tt> operation adds another value to the list. This technique is
simpler and faster than an equivalent technique using <a class="reference internal" href="stdtypes.html#dict.setdefault" title="dict.setdefault"><tt class="xref py py-meth docutils literal"><span class="pre">dict.setdefault()</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="o">.</span><span class="n">setdefault</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="p">[])</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;blue&#39;, [2, 4]), (&#39;red&#39;, [1]), (&#39;yellow&#39;, [1, 3])]</span>
</pre></div>
</div>
<p>Setting the <tt class="xref py py-attr docutils literal"><span class="pre">default_factory</span></tt> to <a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a> makes the
<a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><tt class="xref py py-class docutils literal"><span class="pre">defaultdict</span></tt></a> useful for counting (like a bag or multiset in other
languages):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s">&#39;mississippi&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;i&#39;, 4), (&#39;p&#39;, 2), (&#39;s&#39;, 4), (&#39;m&#39;, 1)]</span>
</pre></div>
</div>
<p>When a letter is first encountered, it is missing from the mapping, so the
<tt class="xref py py-attr docutils literal"><span class="pre">default_factory</span></tt> function calls <a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-func docutils literal"><span class="pre">int()</span></tt></a> to supply a default count of
zero.  The increment operation then builds up the count for each letter.</p>
<p>The function <a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-func docutils literal"><span class="pre">int()</span></tt></a> which always returns zero is just a special case of
constant functions.  A faster and more flexible way to create constant functions
is to use <a class="reference internal" href="itertools.html#itertools.repeat" title="itertools.repeat"><tt class="xref py py-func docutils literal"><span class="pre">itertools.repeat()</span></tt></a> which can supply any constant value (not just
zero):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">constant_factory</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">itertools</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="n">value</span><span class="p">)</span><span class="o">.</span><span class="n">next</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="n">constant_factory</span><span class="p">(</span><span class="s">&#39;&lt;missing&gt;&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&#39;John&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&#39;ran&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;</span><span class="si">%(name)s</span><span class="s"> </span><span class="si">%(action)s</span><span class="s"> to </span><span class="si">%(object)s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">d</span>
<span class="go">&#39;John ran to &lt;missing&gt;&#39;</span>
</pre></div>
</div>
<p>Setting the <tt class="xref py py-attr docutils literal"><span class="pre">default_factory</span></tt> to <a class="reference internal" href="stdtypes.html#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> makes the
<a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><tt class="xref py py-class docutils literal"><span class="pre">defaultdict</span></tt></a> useful for building a dictionary of sets:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&#39;red&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;red&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;red&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">set</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;blue&#39;, set([2, 4])), (&#39;red&#39;, set([1, 3]))]</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="namedtuple-factory-function-for-tuples-with-named-fields">
<h2>8.3.4. <a class="reference internal" href="#collections.namedtuple" title="collections.namedtuple"><tt class="xref py py-func docutils literal"><span class="pre">namedtuple()</span></tt></a> Factory Function for Tuples with Named Fields<a class="headerlink" href="#namedtuple-factory-function-for-tuples-with-named-fields" title="Permalink to this headline">¶</a></h2>
<p>Named tuples assign meaning to each position in a tuple and allow for more readable,
self-documenting code.  They can be used wherever regular tuples are used, and
they add the ability to access fields by name instead of position index.</p>
<dl class="function">
<dt id="collections.namedtuple">
<tt class="descclassname">collections.</tt><tt class="descname">namedtuple</tt><big>(</big><em>typename</em>, <em>field_names</em><span class="optional">[</span>, <em>verbose=False</em><span class="optional">]</span><span class="optional">[</span>, <em>rename=False</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#collections.namedtuple" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new tuple subclass named <em>typename</em>.  The new subclass is used to
create tuple-like objects that have fields accessible by attribute lookup as
well as being indexable and iterable.  Instances of the subclass also have a
helpful docstring (with typename and field_names) and a helpful <a class="reference internal" href="../reference/datamodel.html#object.__repr__" title="object.__repr__"><tt class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></tt></a>
method which lists the tuple contents in a <tt class="docutils literal"><span class="pre">name=value</span></tt> format.</p>
<p>The <em>field_names</em> are a sequence of strings such as <tt class="docutils literal"><span class="pre">['x',</span> <span class="pre">'y']</span></tt>.
Alternatively, <em>field_names</em> can be a single string with each fieldname
separated by whitespace and/or commas, for example <tt class="docutils literal"><span class="pre">'x</span> <span class="pre">y'</span></tt> or <tt class="docutils literal"><span class="pre">'x,</span> <span class="pre">y'</span></tt>.</p>
<p>Any valid Python identifier may be used for a fieldname except for names
starting with an underscore.  Valid identifiers consist of letters, digits,
and underscores but do not start with a digit or underscore and cannot be
a <a class="reference internal" href="keyword.html#module-keyword" title="keyword: Test whether a string is a keyword in Python."><tt class="xref py py-mod docutils literal"><span class="pre">keyword</span></tt></a> such as <em>class</em>, <em>for</em>, <em>return</em>, <em>global</em>, <em>pass</em>, <em>print</em>,
or <em>raise</em>.</p>
<p>If <em>rename</em> is true, invalid fieldnames are automatically replaced
with positional names.  For example, <tt class="docutils literal"><span class="pre">['abc',</span> <span class="pre">'def',</span> <span class="pre">'ghi',</span> <span class="pre">'abc']</span></tt> is
converted to <tt class="docutils literal"><span class="pre">['abc',</span> <span class="pre">'_1',</span> <span class="pre">'ghi',</span> <span class="pre">'_3']</span></tt>, eliminating the keyword
<tt class="docutils literal"><span class="pre">def</span></tt> and the duplicate fieldname <tt class="docutils literal"><span class="pre">abc</span></tt>.</p>
<p>If <em>verbose</em> is true, the class definition is printed just before being built.</p>
<p>Named tuple instances do not have per-instance dictionaries, so they are
lightweight and require no more memory than regular tuples.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.6.</span></p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 2.7: </span>added support for <em>rename</em>.</p>
</dd></dl>

<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;Point&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s">&#39;x&#39;</span><span class="p">,</span> <span class="s">&#39;y&#39;</span><span class="p">],</span> <span class="n">verbose</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="go">class Point(tuple):</span>
<span class="go">    &#39;Point(x, y)&#39;</span>

<span class="go">    __slots__ = ()</span>

<span class="go">    _fields = (&#39;x&#39;, &#39;y&#39;)</span>

<span class="go">    def __new__(_cls, x, y):</span>
<span class="go">        &#39;Create a new instance of Point(x, y)&#39;</span>
<span class="go">        return _tuple.__new__(_cls, (x, y))</span>

<span class="go">    @classmethod</span>
<span class="go">    def _make(cls, iterable, new=tuple.__new__, len=len):</span>
<span class="go">        &#39;Make a new Point object from a sequence or iterable&#39;</span>
<span class="go">        result = new(cls, iterable)</span>
<span class="go">        if len(result) != 2:</span>
<span class="go">            raise TypeError(&#39;Expected 2 arguments, got %d&#39; % len(result))</span>
<span class="go">        return result</span>

<span class="go">    def __repr__(self):</span>
<span class="go">        &#39;Return a nicely formatted representation string&#39;</span>
<span class="go">        return &#39;Point(x=%r, y=%r)&#39; % self</span>

<span class="go">    def _asdict(self):</span>
<span class="go">        &#39;Return a new OrderedDict which maps field names to their values&#39;</span>
<span class="go">        return OrderedDict(zip(self._fields, self))</span>

<span class="go">    def _replace(_self, **kwds):</span>
<span class="go">        &#39;Return a new Point object replacing specified fields with new values&#39;</span>
<span class="go">        result = _self._make(map(kwds.pop, (&#39;x&#39;, &#39;y&#39;), _self))</span>
<span class="go">        if kwds:</span>
<span class="go">            raise ValueError(&#39;Got unexpected field names: %r&#39; % kwds.keys())</span>
<span class="go">        return result</span>

<span class="go">    def __getnewargs__(self):</span>
<span class="go">        &#39;Return self as a plain tuple.   Used by copy and pickle.&#39;</span>
<span class="go">        return tuple(self)</span>

<span class="go">    x = _property(_itemgetter(0), doc=&#39;Alias for field number 0&#39;)</span>

<span class="go">    y = _property(_itemgetter(1), doc=&#39;Alias for field number 1&#39;)</span>


<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="mi">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">22</span><span class="p">)</span>     <span class="c"># instantiate with positional or keyword arguments</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">+</span> <span class="n">p</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>             <span class="c"># indexable like the plain tuple (11, 22)</span>
<span class="go">33</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">p</span>                <span class="c"># unpack like a regular tuple</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span>
<span class="go">(11, 22)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">x</span> <span class="o">+</span> <span class="n">p</span><span class="o">.</span><span class="n">y</span>               <span class="c"># fields also accessible by name</span>
<span class="go">33</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span>                       <span class="c"># readable __repr__ with a name=value style</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
<p>Named tuples are especially useful for assigning field names to result tuples returned
by the <a class="reference internal" href="csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><tt class="xref py py-mod docutils literal"><span class="pre">csv</span></tt></a> or <a class="reference internal" href="sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><tt class="xref py py-mod docutils literal"><span class="pre">sqlite3</span></tt></a> modules:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">EmployeeRecord</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;EmployeeRecord&#39;</span><span class="p">,</span> <span class="s">&#39;name, age, title, department, paygrade&#39;</span><span class="p">)</span>

<span class="kn">import</span> <span class="nn">csv</span>
<span class="k">for</span> <span class="n">emp</span> <span class="ow">in</span> <span class="nb">map</span><span class="p">(</span><span class="n">EmployeeRecord</span><span class="o">.</span><span class="n">_make</span><span class="p">,</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="s">&quot;employees.csv&quot;</span><span class="p">,</span> <span class="s">&quot;rb&quot;</span><span class="p">))):</span>
    <span class="k">print</span> <span class="n">emp</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">emp</span><span class="o">.</span><span class="n">title</span>

<span class="kn">import</span> <span class="nn">sqlite3</span>
<span class="n">conn</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s">&#39;/companydata&#39;</span><span class="p">)</span>
<span class="n">cursor</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&#39;SELECT name, age, title, department, paygrade FROM employees&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">emp</span> <span class="ow">in</span> <span class="nb">map</span><span class="p">(</span><span class="n">EmployeeRecord</span><span class="o">.</span><span class="n">_make</span><span class="p">,</span> <span class="n">cursor</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()):</span>
    <span class="k">print</span> <span class="n">emp</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">emp</span><span class="o">.</span><span class="n">title</span>
</pre></div>
</div>
<p>In addition to the methods inherited from tuples, named tuples support
three additional methods and one attribute.  To prevent conflicts with
field names, the method and attribute names start with an underscore.</p>
<dl class="classmethod">
<dt id="collections.somenamedtuple._make">
<em class="property">classmethod </em><tt class="descclassname">somenamedtuple.</tt><tt class="descname">_make</tt><big>(</big><em>iterable</em><big>)</big><a class="headerlink" href="#collections.somenamedtuple._make" title="Permalink to this definition">¶</a></dt>
<dd><p>Class method that makes a new instance from an existing sequence or iterable.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="p">[</span><span class="mi">11</span><span class="p">,</span> <span class="mi">22</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span><span class="o">.</span><span class="n">_make</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.somenamedtuple._asdict">
<tt class="descclassname">somenamedtuple.</tt><tt class="descname">_asdict</tt><big>(</big><big>)</big><a class="headerlink" href="#collections.somenamedtuple._asdict" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><tt class="xref py py-class docutils literal"><span class="pre">OrderedDict</span></tt></a> which maps field names to their corresponding
values:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_asdict</span><span class="p">()</span>
<span class="go">OrderedDict([(&#39;x&#39;, 11), (&#39;y&#39;, 22)])</span>
</pre></div>
</div>
<p class="versionchanged">
<span class="versionmodified">Changed in version 2.7: </span>Returns an <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><tt class="xref py py-class docutils literal"><span class="pre">OrderedDict</span></tt></a> instead of a regular <a class="reference internal" href="stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a>.</p>
</dd></dl>

<dl class="method">
<dt id="collections.somenamedtuple._replace">
<tt class="descclassname">somenamedtuple.</tt><tt class="descname">_replace</tt><big>(</big><em>kwargs</em><big>)</big><a class="headerlink" href="#collections.somenamedtuple._replace" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new instance of the named tuple replacing specified fields with new
values:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">22</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">33</span><span class="p">)</span>
<span class="go">Point(x=33, y=22)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">partnum</span><span class="p">,</span> <span class="n">record</span> <span class="ow">in</span> <span class="n">inventory</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="go">        inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="collections.somenamedtuple._fields">
<tt class="descclassname">somenamedtuple.</tt><tt class="descname">_fields</tt><a class="headerlink" href="#collections.somenamedtuple._fields" title="Permalink to this definition">¶</a></dt>
<dd><p>Tuple of strings listing the field names.  Useful for introspection
and for creating new named tuple types from existing named tuples.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_fields</span>            <span class="c"># view the field names</span>
<span class="go">(&#39;x&#39;, &#39;y&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Color</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;Color&#39;</span><span class="p">,</span> <span class="s">&#39;red green blue&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Pixel</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;Pixel&#39;</span><span class="p">,</span> <span class="n">Point</span><span class="o">.</span><span class="n">_fields</span> <span class="o">+</span> <span class="n">Color</span><span class="o">.</span><span class="n">_fields</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Pixel</span><span class="p">(</span><span class="mi">11</span><span class="p">,</span> <span class="mi">22</span><span class="p">,</span> <span class="mi">128</span><span class="p">,</span> <span class="mi">255</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="go">Pixel(x=11, y=22, red=128, green=255, blue=0)</span>
</pre></div>
</div>
</dd></dl>

<p>To retrieve a field whose name is stored in a string, use the <a class="reference internal" href="functions.html#getattr" title="getattr"><tt class="xref py py-func docutils literal"><span class="pre">getattr()</span></tt></a>
function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">getattr</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="s">&#39;x&#39;</span><span class="p">)</span>
<span class="go">11</span>
</pre></div>
</div>
<p>To convert a dictionary to a named tuple, use the double-star-operator
(as described in <a class="reference internal" href="../tutorial/controlflow.html#tut-unpacking-arguments"><em>Unpacking Argument Lists</em></a>):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s">&#39;x&#39;</span><span class="p">:</span> <span class="mi">11</span><span class="p">,</span> <span class="s">&#39;y&#39;</span><span class="p">:</span> <span class="mi">22</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span><span class="p">(</span><span class="o">**</span><span class="n">d</span><span class="p">)</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
<p>Since a named tuple is a regular Python class, it is easy to add or change
functionality with a subclass.  Here is how to add a calculated field and
a fixed-width print format:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;Point&#39;</span><span class="p">,</span> <span class="s">&#39;x y&#39;</span><span class="p">)):</span>
<span class="go">        __slots__ = ()</span>
<span class="go">        @property</span>
<span class="go">        def hypot(self):</span>
<span class="go">            return (self.x ** 2 + self.y ** 2) ** 0.5</span>
<span class="go">        def __str__(self):</span>
<span class="go">            return &#39;Point: x=%6.3f  y=%6.3f  hypot=%6.3f&#39; % (self.x, self.y, self.hypot)</span>
</pre></div>
</div>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">Point</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="n">Point</span><span class="p">(</span><span class="mi">14</span><span class="p">,</span> <span class="mi">5</span><span class="o">/</span><span class="mf">7.</span><span class="p">):</span>
<span class="go">        print p</span>
<span class="go">Point: x= 3.000  y= 4.000  hypot= 5.000</span>
<span class="go">Point: x=14.000  y= 0.714  hypot=14.018</span>
</pre></div>
</div>
<p>The subclass shown above sets <tt class="docutils literal"><span class="pre">__slots__</span></tt> to an empty tuple.  This helps
keep memory requirements low by preventing the creation of instance dictionaries.</p>
<p>Subclassing is not useful for adding new, stored fields.  Instead, simply
create a new named tuple type from the <tt class="xref py py-attr docutils literal"><span class="pre">_fields</span></tt> attribute:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Point3D</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;Point3D&#39;</span><span class="p">,</span> <span class="n">Point</span><span class="o">.</span><span class="n">_fields</span> <span class="o">+</span> <span class="p">(</span><span class="s">&#39;z&#39;</span><span class="p">,))</span>
</pre></div>
</div>
<p>Default values can be implemented by using <tt class="xref py py-meth docutils literal"><span class="pre">_replace()</span></tt> to
customize a prototype instance:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Account</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;Account&#39;</span><span class="p">,</span> <span class="s">&#39;owner balance transaction_count&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">default_account</span> <span class="o">=</span> <span class="n">Account</span><span class="p">(</span><span class="s">&#39;&lt;owner name&gt;&#39;</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">johns_account</span> <span class="o">=</span> <span class="n">default_account</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">owner</span><span class="o">=</span><span class="s">&#39;John&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Enumerated constants can be implemented with named tuples, but it is simpler
and more efficient to use a simple class declaration:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Status</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;Status&#39;</span><span class="p">,</span> <span class="s">&#39;open pending closed&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">_make</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Status</span><span class="o">.</span><span class="n">open</span><span class="p">,</span> <span class="n">Status</span><span class="o">.</span><span class="n">pending</span><span class="p">,</span> <span class="n">Status</span><span class="o">.</span><span class="n">closed</span>
<span class="go">(0, 1, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Status</span><span class="p">:</span>
<span class="go">        open, pending, closed = range(3)</span>
</pre></div>
</div>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="http://code.activestate.com/recipes/500261/">Named tuple recipe</a>
adapted for Python 2.4.</p>
</div>
</div>
<div class="section" id="ordereddict-objects">
<h2>8.3.5. <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><tt class="xref py py-class docutils literal"><span class="pre">OrderedDict</span></tt></a> objects<a class="headerlink" href="#ordereddict-objects" title="Permalink to this headline">¶</a></h2>
<p>Ordered dictionaries are just like regular dictionaries but they remember the
order that items were inserted.  When iterating over an ordered dictionary,
the items are returned in the order their keys were first added.</p>
<dl class="class">
<dt id="collections.OrderedDict">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">OrderedDict</tt><big>(</big><span class="optional">[</span><em>items</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#collections.OrderedDict" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an instance of a dict subclass, supporting the usual <a class="reference internal" href="stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a>
methods.  An <em>OrderedDict</em> is a dict that remembers the order that keys
were first inserted. If a new entry overwrites an existing entry, the
original insertion position is left unchanged.  Deleting an entry and
reinserting it will move it to the end.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.7.</span></p>
</dd></dl>

<dl class="method">
<dt id="collections.OrderedDict.popitem">
<tt class="descclassname">OrderedDict.</tt><tt class="descname">popitem</tt><big>(</big><em>last=True</em><big>)</big><a class="headerlink" href="#collections.OrderedDict.popitem" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#collections.OrderedDict.popitem" title="collections.OrderedDict.popitem"><tt class="xref py py-meth docutils literal"><span class="pre">popitem()</span></tt></a> method for ordered dictionaries returns and removes
a (key, value) pair.  The pairs are returned in LIFO order if <em>last</em> is
true or FIFO order if false.</p>
</dd></dl>

<p>In addition to the usual mapping methods, ordered dictionaries also support
reverse iteration using <a class="reference internal" href="functions.html#reversed" title="reversed"><tt class="xref py py-func docutils literal"><span class="pre">reversed()</span></tt></a>.</p>
<p>Equality tests between <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><tt class="xref py py-class docutils literal"><span class="pre">OrderedDict</span></tt></a> objects are order-sensitive
and are implemented as <tt class="docutils literal"><span class="pre">list(od1.items())==list(od2.items())</span></tt>.
Equality tests between <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><tt class="xref py py-class docutils literal"><span class="pre">OrderedDict</span></tt></a> objects and other
<a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><tt class="xref py py-class docutils literal"><span class="pre">Mapping</span></tt></a> objects are order-insensitive like regular dictionaries.
This allows <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><tt class="xref py py-class docutils literal"><span class="pre">OrderedDict</span></tt></a> objects to be substituted anywhere a
regular dictionary is used.</p>
<p>The <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><tt class="xref py py-class docutils literal"><span class="pre">OrderedDict</span></tt></a> constructor and <tt class="xref py py-meth docutils literal"><span class="pre">update()</span></tt> method both accept
keyword arguments, but their order is lost because Python&#8217;s function call
semantics pass-in keyword arguments using a regular unordered dictionary.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="http://code.activestate.com/recipes/576693/">Equivalent OrderedDict recipe</a>
that runs on Python 2.4 or later.</p>
</div>
<div class="section" id="ordereddict-examples-and-recipes">
<h3>8.3.5.1. <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><tt class="xref py py-class docutils literal"><span class="pre">OrderedDict</span></tt></a> Examples and Recipes<a class="headerlink" href="#ordereddict-examples-and-recipes" title="Permalink to this headline">¶</a></h3>
<p>Since an ordered dictionary remembers its insertion order, it can be used
in conjuction with sorting to make a sorted dictionary:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="c"># regular unsorted dictionary</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s">&#39;banana&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s">&#39;apple&#39;</span><span class="p">:</span><span class="mi">4</span><span class="p">,</span> <span class="s">&#39;pear&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s">&#39;orange&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">}</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c"># dictionary sorted by key</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">OrderedDict</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">t</span><span class="p">:</span> <span class="n">t</span><span class="p">[</span><span class="mi">0</span><span class="p">]))</span>
<span class="go">OrderedDict([(&#39;apple&#39;, 4), (&#39;banana&#39;, 3), (&#39;orange&#39;, 2), (&#39;pear&#39;, 1)])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c"># dictionary sorted by value</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">OrderedDict</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">t</span><span class="p">:</span> <span class="n">t</span><span class="p">[</span><span class="mi">1</span><span class="p">]))</span>
<span class="go">OrderedDict([(&#39;pear&#39;, 1), (&#39;orange&#39;, 2), (&#39;banana&#39;, 3), (&#39;apple&#39;, 4)])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c"># dictionary sorted by length of the key string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">OrderedDict</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">t</span><span class="p">:</span> <span class="nb">len</span><span class="p">(</span><span class="n">t</span><span class="p">[</span><span class="mi">0</span><span class="p">])))</span>
<span class="go">OrderedDict([(&#39;pear&#39;, 1), (&#39;apple&#39;, 4), (&#39;orange&#39;, 2), (&#39;banana&#39;, 3)])</span>
</pre></div>
</div>
<p>The new sorted dictionaries maintain their sort order when entries
are deleted.  But when new keys are added, the keys are appended
to the end and the sort is not maintained.</p>
<p>It is also straight-forward to create an ordered dictionary variant
that remembers the order the keys were <em>last</em> inserted.
If a new entry overwrites an existing entry, the
original insertion position is changed and moved to the end:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">LastUpdatedOrderedDict</span><span class="p">(</span><span class="n">OrderedDict</span><span class="p">):</span>
    <span class="s">&#39;Store items in the order the keys were last added&#39;</span>

    <span class="k">def</span> <span class="nf">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="bp">self</span><span class="p">:</span>
            <span class="k">del</span> <span class="bp">self</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
        <span class="n">OrderedDict</span><span class="o">.</span><span class="n">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
<p>An ordered dictionary can be combined with the <a class="reference internal" href="#collections.Counter" title="collections.Counter"><tt class="xref py py-class docutils literal"><span class="pre">Counter</span></tt></a> class
so that the counter remembers the order elements are first encountered:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">OrderedCounter</span><span class="p">(</span><span class="n">Counter</span><span class="p">,</span> <span class="n">OrderedDict</span><span class="p">):</span>
     <span class="s">&#39;Counter that remembers the order elements are first encountered&#39;</span>

     <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
         <span class="k">return</span> <span class="s">&#39;</span><span class="si">%s</span><span class="s">(</span><span class="si">%r</span><span class="s">)&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">__class__</span><span class="o">.</span><span class="n">__name__</span><span class="p">,</span> <span class="n">OrderedDict</span><span class="p">(</span><span class="bp">self</span><span class="p">))</span>

     <span class="k">def</span> <span class="nf">__reduce__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
         <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">__class__</span><span class="p">,</span> <span class="p">(</span><span class="n">OrderedDict</span><span class="p">(</span><span class="bp">self</span><span class="p">),)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="collections-abstract-base-classes">
<span id="id1"></span><h2>8.3.6. Collections Abstract Base Classes<a class="headerlink" href="#collections-abstract-base-classes" title="Permalink to this headline">¶</a></h2>
<p>The collections module offers the following <a class="reference internal" href="../glossary.html#term-abstract-base-class"><em class="xref std std-term">ABCs</em></a>:</p>
<table border="1" class="docutils">
<colgroup>
<col width="21%" />
<col width="18%" />
<col width="18%" />
<col width="43%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">ABC</th>
<th class="head">Inherits from</th>
<th class="head">Abstract Methods</th>
<th class="head">Mixin Methods</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="#collections.Container" title="collections.Container"><tt class="xref py py-class docutils literal"><span class="pre">Container</span></tt></a></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__contains__</span></tt></td>
<td>&nbsp;</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.Hashable" title="collections.Hashable"><tt class="xref py py-class docutils literal"><span class="pre">Hashable</span></tt></a></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__hash__</span></tt></td>
<td>&nbsp;</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><tt class="xref py py-class docutils literal"><span class="pre">Iterable</span></tt></a></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__iter__</span></tt></td>
<td>&nbsp;</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.Iterator" title="collections.Iterator"><tt class="xref py py-class docutils literal"><span class="pre">Iterator</span></tt></a></td>
<td><a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><tt class="xref py py-class docutils literal"><span class="pre">Iterable</span></tt></a></td>
<td><tt class="docutils literal"><span class="pre">next</span></tt></td>
<td><tt class="docutils literal"><span class="pre">__iter__</span></tt></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.Sized" title="collections.Sized"><tt class="xref py py-class docutils literal"><span class="pre">Sized</span></tt></a></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__len__</span></tt></td>
<td>&nbsp;</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.Callable" title="collections.Callable"><tt class="xref py py-class docutils literal"><span class="pre">Callable</span></tt></a></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__call__</span></tt></td>
<td>&nbsp;</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.Sequence" title="collections.Sequence"><tt class="xref py py-class docutils literal"><span class="pre">Sequence</span></tt></a></td>
<td><a class="reference internal" href="#collections.Sized" title="collections.Sized"><tt class="xref py py-class docutils literal"><span class="pre">Sized</span></tt></a>,
<a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><tt class="xref py py-class docutils literal"><span class="pre">Iterable</span></tt></a>,
<a class="reference internal" href="#collections.Container" title="collections.Container"><tt class="xref py py-class docutils literal"><span class="pre">Container</span></tt></a></td>
<td><tt class="docutils literal"><span class="pre">__getitem__</span></tt>,
<tt class="docutils literal"><span class="pre">__len__</span></tt></td>
<td><tt class="docutils literal"><span class="pre">__contains__</span></tt>, <tt class="docutils literal"><span class="pre">__iter__</span></tt>, <tt class="docutils literal"><span class="pre">__reversed__</span></tt>,
<tt class="docutils literal"><span class="pre">index</span></tt>, and <tt class="docutils literal"><span class="pre">count</span></tt></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.MutableSequence" title="collections.MutableSequence"><tt class="xref py py-class docutils literal"><span class="pre">MutableSequence</span></tt></a></td>
<td><a class="reference internal" href="#collections.Sequence" title="collections.Sequence"><tt class="xref py py-class docutils literal"><span class="pre">Sequence</span></tt></a></td>
<td><tt class="docutils literal"><span class="pre">__getitem__</span></tt>,
<tt class="docutils literal"><span class="pre">__setitem__</span></tt>,
<tt class="docutils literal"><span class="pre">__delitem__</span></tt>,
<tt class="docutils literal"><span class="pre">__len__</span></tt>,
<tt class="docutils literal"><span class="pre">insert</span></tt></td>
<td>Inherited <a class="reference internal" href="#collections.Sequence" title="collections.Sequence"><tt class="xref py py-class docutils literal"><span class="pre">Sequence</span></tt></a> methods and
<tt class="docutils literal"><span class="pre">append</span></tt>, <tt class="docutils literal"><span class="pre">reverse</span></tt>, <tt class="docutils literal"><span class="pre">extend</span></tt>, <tt class="docutils literal"><span class="pre">pop</span></tt>,
<tt class="docutils literal"><span class="pre">remove</span></tt>, and <tt class="docutils literal"><span class="pre">__iadd__</span></tt></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.Set" title="collections.Set"><tt class="xref py py-class docutils literal"><span class="pre">Set</span></tt></a></td>
<td><a class="reference internal" href="#collections.Sized" title="collections.Sized"><tt class="xref py py-class docutils literal"><span class="pre">Sized</span></tt></a>,
<a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><tt class="xref py py-class docutils literal"><span class="pre">Iterable</span></tt></a>,
<a class="reference internal" href="#collections.Container" title="collections.Container"><tt class="xref py py-class docutils literal"><span class="pre">Container</span></tt></a></td>
<td><tt class="docutils literal"><span class="pre">__contains__</span></tt>,
<tt class="docutils literal"><span class="pre">__iter__</span></tt>,
<tt class="docutils literal"><span class="pre">__len__</span></tt></td>
<td><tt class="docutils literal"><span class="pre">__le__</span></tt>, <tt class="docutils literal"><span class="pre">__lt__</span></tt>, <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">__gt__</span></tt>, <tt class="docutils literal"><span class="pre">__ge__</span></tt>, <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">__sub__</span></tt>, <tt class="docutils literal"><span class="pre">__xor__</span></tt>, and <tt class="docutils literal"><span class="pre">isdisjoint</span></tt></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.MutableSet" title="collections.MutableSet"><tt class="xref py py-class docutils literal"><span class="pre">MutableSet</span></tt></a></td>
<td><a class="reference internal" href="#collections.Set" title="collections.Set"><tt class="xref py py-class docutils literal"><span class="pre">Set</span></tt></a></td>
<td><tt class="docutils literal"><span class="pre">__contains__</span></tt>,
<tt class="docutils literal"><span class="pre">__iter__</span></tt>,
<tt class="docutils literal"><span class="pre">__len__</span></tt>,
<tt class="docutils literal"><span class="pre">add</span></tt>,
<tt class="docutils literal"><span class="pre">discard</span></tt></td>
<td>Inherited <a class="reference internal" href="#collections.Set" title="collections.Set"><tt class="xref py py-class docutils literal"><span class="pre">Set</span></tt></a> methods and
<tt class="docutils literal"><span class="pre">clear</span></tt>, <tt class="docutils literal"><span class="pre">pop</span></tt>, <tt class="docutils literal"><span class="pre">remove</span></tt>, <tt class="docutils literal"><span class="pre">__ior__</span></tt>,
<tt class="docutils literal"><span class="pre">__iand__</span></tt>, <tt class="docutils literal"><span class="pre">__ixor__</span></tt>, and <tt class="docutils literal"><span class="pre">__isub__</span></tt></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><tt class="xref py py-class docutils literal"><span class="pre">Mapping</span></tt></a></td>
<td><a class="reference internal" href="#collections.Sized" title="collections.Sized"><tt class="xref py py-class docutils literal"><span class="pre">Sized</span></tt></a>,
<a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><tt class="xref py py-class docutils literal"><span class="pre">Iterable</span></tt></a>,
<a class="reference internal" href="#collections.Container" title="collections.Container"><tt class="xref py py-class docutils literal"><span class="pre">Container</span></tt></a></td>
<td><tt class="docutils literal"><span class="pre">__getitem__</span></tt>,
<tt class="docutils literal"><span class="pre">__iter__</span></tt>,
<tt class="docutils literal"><span class="pre">__len__</span></tt></td>
<td><tt class="docutils literal"><span class="pre">__contains__</span></tt>, <tt class="docutils literal"><span class="pre">keys</span></tt>, <tt class="docutils literal"><span class="pre">items</span></tt>, <tt class="docutils literal"><span class="pre">values</span></tt>,
<tt class="docutils literal"><span class="pre">get</span></tt>, <tt class="docutils literal"><span class="pre">__eq__</span></tt>, and <tt class="docutils literal"><span class="pre">__ne__</span></tt></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.MutableMapping" title="collections.MutableMapping"><tt class="xref py py-class docutils literal"><span class="pre">MutableMapping</span></tt></a></td>
<td><a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><tt class="xref py py-class docutils literal"><span class="pre">Mapping</span></tt></a></td>
<td><tt class="docutils literal"><span class="pre">__getitem__</span></tt>,
<tt class="docutils literal"><span class="pre">__setitem__</span></tt>,
<tt class="docutils literal"><span class="pre">__delitem__</span></tt>,
<tt class="docutils literal"><span class="pre">__iter__</span></tt>,
<tt class="docutils literal"><span class="pre">__len__</span></tt></td>
<td>Inherited <a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><tt class="xref py py-class docutils literal"><span class="pre">Mapping</span></tt></a> methods and
<tt class="docutils literal"><span class="pre">pop</span></tt>, <tt class="docutils literal"><span class="pre">popitem</span></tt>, <tt class="docutils literal"><span class="pre">clear</span></tt>, <tt class="docutils literal"><span class="pre">update</span></tt>,
and <tt class="docutils literal"><span class="pre">setdefault</span></tt></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><tt class="xref py py-class docutils literal"><span class="pre">MappingView</span></tt></a></td>
<td><a class="reference internal" href="#collections.Sized" title="collections.Sized"><tt class="xref py py-class docutils literal"><span class="pre">Sized</span></tt></a></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__len__</span></tt></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.ItemsView" title="collections.ItemsView"><tt class="xref py py-class docutils literal"><span class="pre">ItemsView</span></tt></a></td>
<td><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><tt class="xref py py-class docutils literal"><span class="pre">MappingView</span></tt></a>,
<a class="reference internal" href="#collections.Set" title="collections.Set"><tt class="xref py py-class docutils literal"><span class="pre">Set</span></tt></a></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__contains__</span></tt>,
<tt class="docutils literal"><span class="pre">__iter__</span></tt></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.KeysView" title="collections.KeysView"><tt class="xref py py-class docutils literal"><span class="pre">KeysView</span></tt></a></td>
<td><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><tt class="xref py py-class docutils literal"><span class="pre">MappingView</span></tt></a>,
<a class="reference internal" href="#collections.Set" title="collections.Set"><tt class="xref py py-class docutils literal"><span class="pre">Set</span></tt></a></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__contains__</span></tt>,
<tt class="docutils literal"><span class="pre">__iter__</span></tt></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.ValuesView" title="collections.ValuesView"><tt class="xref py py-class docutils literal"><span class="pre">ValuesView</span></tt></a></td>
<td><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><tt class="xref py py-class docutils literal"><span class="pre">MappingView</span></tt></a></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__contains__</span></tt>, <tt class="docutils literal"><span class="pre">__iter__</span></tt></td>
</tr>
</tbody>
</table>
<dl class="class">
<dt id="collections.Container">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">Container</tt><a class="headerlink" href="#collections.Container" title="Permalink to this definition">¶</a></dt>
<dt id="collections.Hashable">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">Hashable</tt><a class="headerlink" href="#collections.Hashable" title="Permalink to this definition">¶</a></dt>
<dt id="collections.Sized">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">Sized</tt><a class="headerlink" href="#collections.Sized" title="Permalink to this definition">¶</a></dt>
<dt id="collections.Callable">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">Callable</tt><a class="headerlink" href="#collections.Callable" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for classes that provide respectively the methods <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><tt class="xref py py-meth docutils literal"><span class="pre">__contains__()</span></tt></a>,
<a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a>, <a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><tt class="xref py py-meth docutils literal"><span class="pre">__len__()</span></tt></a>, and <a class="reference internal" href="../reference/datamodel.html#object.__call__" title="object.__call__"><tt class="xref py py-meth docutils literal"><span class="pre">__call__()</span></tt></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Iterable">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">Iterable</tt><a class="headerlink" href="#collections.Iterable" title="Permalink to this definition">¶</a></dt>
<dd><p>ABC for classes that provide the <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><tt class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></tt></a> method.
See also the definition of <a class="reference internal" href="../glossary.html#term-iterable"><em class="xref std std-term">iterable</em></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Iterator">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">Iterator</tt><a class="headerlink" href="#collections.Iterator" title="Permalink to this definition">¶</a></dt>
<dd><p>ABC for classes that provide the <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><tt class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></tt></a> and <a class="reference internal" href="functions.html#next" title="next"><tt class="xref py py-meth docutils literal"><span class="pre">next()</span></tt></a> methods.
See also the definition of <a class="reference internal" href="../glossary.html#term-iterator"><em class="xref std std-term">iterator</em></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Sequence">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">Sequence</tt><a class="headerlink" href="#collections.Sequence" title="Permalink to this definition">¶</a></dt>
<dt id="collections.MutableSequence">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">MutableSequence</tt><a class="headerlink" href="#collections.MutableSequence" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for read-only and mutable <a class="reference internal" href="../glossary.html#term-sequence"><em class="xref std std-term">sequences</em></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Set">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">Set</tt><a class="headerlink" href="#collections.Set" title="Permalink to this definition">¶</a></dt>
<dt id="collections.MutableSet">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">MutableSet</tt><a class="headerlink" href="#collections.MutableSet" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for read-only and mutable sets.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Mapping">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">Mapping</tt><a class="headerlink" href="#collections.Mapping" title="Permalink to this definition">¶</a></dt>
<dt id="collections.MutableMapping">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">MutableMapping</tt><a class="headerlink" href="#collections.MutableMapping" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for read-only and mutable <a class="reference internal" href="../glossary.html#term-mapping"><em class="xref std std-term">mappings</em></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.MappingView">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">MappingView</tt><a class="headerlink" href="#collections.MappingView" title="Permalink to this definition">¶</a></dt>
<dt id="collections.ItemsView">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">ItemsView</tt><a class="headerlink" href="#collections.ItemsView" title="Permalink to this definition">¶</a></dt>
<dt id="collections.KeysView">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">KeysView</tt><a class="headerlink" href="#collections.KeysView" title="Permalink to this definition">¶</a></dt>
<dt id="collections.ValuesView">
<em class="property">class </em><tt class="descclassname">collections.</tt><tt class="descname">ValuesView</tt><a class="headerlink" href="#collections.ValuesView" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for mapping, items, keys, and values <a class="reference internal" href="../glossary.html#term-view"><em class="xref std std-term">views</em></a>.</p>
</dd></dl>

<p>These ABCs allow us to ask classes or instances if they provide
particular functionality, for example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">size</span> <span class="o">=</span> <span class="bp">None</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">myvar</span><span class="p">,</span> <span class="n">collections</span><span class="o">.</span><span class="n">Sized</span><span class="p">):</span>
    <span class="n">size</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">myvar</span><span class="p">)</span>
</pre></div>
</div>
<p>Several of the ABCs are also useful as mixins that make it easier to develop
classes supporting container APIs.  For example, to write a class supporting
the full <a class="reference internal" href="#collections.Set" title="collections.Set"><tt class="xref py py-class docutils literal"><span class="pre">Set</span></tt></a> API, it only necessary to supply the three underlying
abstract methods: <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><tt class="xref py py-meth docutils literal"><span class="pre">__contains__()</span></tt></a>, <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><tt class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></tt></a>, and <a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><tt class="xref py py-meth docutils literal"><span class="pre">__len__()</span></tt></a>.
The ABC supplies the remaining methods such as <a class="reference internal" href="../reference/datamodel.html#object.__and__" title="object.__and__"><tt class="xref py py-meth docutils literal"><span class="pre">__and__()</span></tt></a> and
<tt class="xref py py-meth docutils literal"><span class="pre">isdisjoint()</span></tt></p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">ListBasedSet</span><span class="p">(</span><span class="n">collections</span><span class="o">.</span><span class="n">Set</span><span class="p">):</span>
     <span class="sd">&#39;&#39;&#39; Alternate set implementation favoring space over speed</span>
<span class="sd">         and not requiring the set elements to be hashable. &#39;&#39;&#39;</span>
     <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
         <span class="bp">self</span><span class="o">.</span><span class="n">elements</span> <span class="o">=</span> <span class="n">lst</span> <span class="o">=</span> <span class="p">[]</span>
         <span class="k">for</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
             <span class="k">if</span> <span class="n">value</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">lst</span><span class="p">:</span>
                 <span class="n">lst</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
     <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
         <span class="k">return</span> <span class="nb">iter</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">)</span>
     <span class="k">def</span> <span class="nf">__contains__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
         <span class="k">return</span> <span class="n">value</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">elements</span>
     <span class="k">def</span> <span class="nf">__len__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
         <span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">)</span>

<span class="n">s1</span> <span class="o">=</span> <span class="n">ListBasedSet</span><span class="p">(</span><span class="s">&#39;abcdef&#39;</span><span class="p">)</span>
<span class="n">s2</span> <span class="o">=</span> <span class="n">ListBasedSet</span><span class="p">(</span><span class="s">&#39;defghi&#39;</span><span class="p">)</span>
<span class="n">overlap</span> <span class="o">=</span> <span class="n">s1</span> <span class="o">&amp;</span> <span class="n">s2</span>            <span class="c"># The __and__() method is supported automatically</span>
</pre></div>
</div>
<p>Notes on using <a class="reference internal" href="#collections.Set" title="collections.Set"><tt class="xref py py-class docutils literal"><span class="pre">Set</span></tt></a> and <a class="reference internal" href="#collections.MutableSet" title="collections.MutableSet"><tt class="xref py py-class docutils literal"><span class="pre">MutableSet</span></tt></a> as a mixin:</p>
<ol class="arabic simple">
<li>Since some set operations create new sets, the default mixin methods need
a way to create new instances from an iterable. The class constructor is
assumed to have a signature in the form <tt class="docutils literal"><span class="pre">ClassName(iterable)</span></tt>.
That assumption is factored-out to an internal classmethod called
<tt class="xref py py-meth docutils literal"><span class="pre">_from_iterable()</span></tt> which calls <tt class="docutils literal"><span class="pre">cls(iterable)</span></tt> to produce a new set.
If the <a class="reference internal" href="#collections.Set" title="collections.Set"><tt class="xref py py-class docutils literal"><span class="pre">Set</span></tt></a> mixin is being used in a class with a different
constructor signature, you will need to override <tt class="xref py py-meth docutils literal"><span class="pre">_from_iterable()</span></tt>
with a classmethod that can construct new instances from
an iterable argument.</li>
<li>To override the comparisons (presumably for speed, as the
semantics are fixed), redefine <a class="reference internal" href="../reference/datamodel.html#object.__le__" title="object.__le__"><tt class="xref py py-meth docutils literal"><span class="pre">__le__()</span></tt></a> and
then the other operations will automatically follow suit.</li>
<li>The <a class="reference internal" href="#collections.Set" title="collections.Set"><tt class="xref py py-class docutils literal"><span class="pre">Set</span></tt></a> mixin provides a <tt class="xref py py-meth docutils literal"><span class="pre">_hash()</span></tt> method to compute a hash value
for the set; however, <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> is not defined because not all sets
are hashable or immutable.  To add set hashabilty using mixins,
inherit from both <a class="reference internal" href="#collections.Set" title="collections.Set"><tt class="xref py py-meth docutils literal"><span class="pre">Set()</span></tt></a> and <a class="reference internal" href="#collections.Hashable" title="collections.Hashable"><tt class="xref py py-meth docutils literal"><span class="pre">Hashable()</span></tt></a>, then define
<tt class="docutils literal"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">Set._hash</span></tt>.</li>
</ol>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<ul class="last simple">
<li><a class="reference external" href="http://code.activestate.com/recipes/576694/">OrderedSet recipe</a> for an
example built on <a class="reference internal" href="#collections.MutableSet" title="collections.MutableSet"><tt class="xref py py-class docutils literal"><span class="pre">MutableSet</span></tt></a>.</li>
<li>For more about ABCs, see the <a class="reference internal" href="abc.html#module-abc" title="abc: Abstract base classes according to PEP 3119."><tt class="xref py py-mod docutils literal"><span class="pre">abc</span></tt></a> module and <span class="target" id="index-0"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-3119"><strong>PEP 3119</strong></a>.</li>
</ul>
</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="#">8.3. <tt class="docutils literal"><span class="pre">collections</span></tt> &#8212; High-performance container datatypes</a><ul>
<li><a class="reference internal" href="#counter-objects">8.3.1. <tt class="docutils literal"><span class="pre">Counter</span></tt> objects</a></li>
<li><a class="reference internal" href="#deque-objects">8.3.2. <tt class="docutils literal"><span class="pre">deque</span></tt> objects</a><ul>
<li><a class="reference internal" href="#deque-recipes">8.3.2.1. <tt class="docutils literal"><span class="pre">deque</span></tt> Recipes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#defaultdict-objects">8.3.3. <tt class="docutils literal"><span class="pre">defaultdict</span></tt> objects</a><ul>
<li><a class="reference internal" href="#defaultdict-examples">8.3.3.1. <tt class="docutils literal"><span class="pre">defaultdict</span></tt> Examples</a></li>
</ul>
</li>
<li><a class="reference internal" href="#namedtuple-factory-function-for-tuples-with-named-fields">8.3.4. <tt class="docutils literal"><span class="pre">namedtuple()</span></tt> Factory Function for Tuples with Named Fields</a></li>
<li><a class="reference internal" href="#ordereddict-objects">8.3.5. <tt class="docutils literal"><span class="pre">OrderedDict</span></tt> objects</a><ul>
<li><a class="reference internal" href="#ordereddict-examples-and-recipes">8.3.5.1. <tt class="docutils literal"><span class="pre">OrderedDict</span></tt> Examples and Recipes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#collections-abstract-base-classes">8.3.6. Collections Abstract Base Classes</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="calendar.html"
                        title="previous chapter">8.2. <tt class="docutils literal"><span class="pre">calendar</span></tt> &#8212; General calendar-related functions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="heapq.html"
                        title="next chapter">8.4. <tt class="docutils literal"><span class="pre">heapq</span></tt> &#8212; Heap queue algorithm</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/library/collections.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="heapq.html" title="8.4. heapq — Heap queue algorithm"
             >next</a> |</li>
        <li class="right" >
          <a href="calendar.html" title="8.2. calendar — General calendar-related functions"
             >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> &raquo;</li>
        <li>
          <a href="../index.html">Python 2.7.5 documentation</a> &raquo;
        </li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="datatypes.html" >8. Data Types</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
    &copy; <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>

Filemanager

Name Type Size Permission Actions
2to3.html File 49.27 KB 0644
__builtin__.html File 10.26 KB 0644
__future__.html File 13.79 KB 0644
__main__.html File 7.05 KB 0644
_winreg.html File 59.21 KB 0644
abc.html File 23.9 KB 0644
aepack.html File 13.16 KB 0644
aetools.html File 14.91 KB 0644
aetypes.html File 18.88 KB 0644
aifc.html File 22.4 KB 0644
al.html File 17.34 KB 0644
allos.html File 33.72 KB 0644
anydbm.html File 16.33 KB 0644
archiving.html File 9.26 KB 0644
argparse.html File 237.62 KB 0644
array.html File 29.29 KB 0644
ast.html File 34.98 KB 0644
asynchat.html File 31.43 KB 0644
asyncore.html File 36.51 KB 0644
atexit.html File 16.8 KB 0644
audioop.html File 31.36 KB 0644
autogil.html File 8.19 KB 0644
base64.html File 19.67 KB 0644
basehttpserver.html File 34.04 KB 0644
bastion.html File 11.04 KB 0644
bdb.html File 36.68 KB 0644
binascii.html File 20.67 KB 0644
binhex.html File 10.58 KB 0644
bisect.html File 23.24 KB 0644
bsddb.html File 26.43 KB 0644
bz2.html File 26.08 KB 0644
calendar.html File 37.79 KB 0644
carbon.html File 48.94 KB 0644
cd.html File 27.96 KB 0644
cgi.html File 49.92 KB 0644
cgihttpserver.html File 13.1 KB 0644
cgitb.html File 11.41 KB 0644
chunk.html File 14.66 KB 0644
cmath.html File 25.63 KB 0644
cmd.html File 26.09 KB 0644
code.html File 24.58 KB 0644
codecs.html File 100.64 KB 0644
codeop.html File 14.84 KB 0644
collections.html File 133.96 KB 0644
colorpicker.html File 7.52 KB 0644
colorsys.html File 11.04 KB 0644
commands.html File 14.36 KB 0644
compileall.html File 16.83 KB 0644
compiler.html File 67.75 KB 0644
configparser.html File 62.13 KB 0644
constants.html File 12.83 KB 0644
contextlib.html File 19.39 KB 0644
cookie.html File 39.07 KB 0644
cookielib.html File 83.82 KB 0644
copy.html File 12.19 KB 0644
copy_reg.html File 13.76 KB 0644
crypt.html File 10.04 KB 0644
crypto.html File 7.59 KB 0644
csv.html File 67.37 KB 0644
ctypes.html File 238.78 KB 0644
curses.ascii.html File 22.29 KB 0644
curses.html File 146.63 KB 0644
curses.panel.html File 14.39 KB 0644
custominterp.html File 7.62 KB 0644
datatypes.html File 16.84 KB 0644
datetime.html File 226.59 KB 0644
dbhash.html File 15.48 KB 0644
dbm.html File 12.07 KB 0644
debug.html File 10.15 KB 0644
decimal.html File 194.44 KB 0644
development.html File 14.17 KB 0644
difflib.html File 84.83 KB 0644
dircache.html File 11.41 KB 0644
dis.html File 69.95 KB 0644
distutils.html File 8.05 KB 0644
dl.html File 16.33 KB 0644
doctest.html File 165.54 KB 0644
docxmlrpcserver.html File 16.43 KB 0644
dumbdbm.html File 14.02 KB 0644
dummy_thread.html File 9.43 KB 0644
dummy_threading.html File 8.37 KB 0644
easydialogs.html File 30.55 KB 0644
email-examples.html File 45.65 KB 0644
email.charset.html File 26.8 KB 0644
email.encoders.html File 11.86 KB 0644
email.errors.html File 15.77 KB 0644
email.generator.html File 20.77 KB 0644
email.header.html File 26.92 KB 0644
email.html File 44.24 KB 0644
email.iterators.html File 11.52 KB 0644
email.message.html File 63.16 KB 0644
email.mime.html File 27.93 KB 0644
email.parser.html File 30.45 KB 0644
email.util.html File 24.46 KB 0644
errno.html File 37.99 KB 0644
exceptions.html File 56.13 KB 0644
fcntl.html File 22.67 KB 0644
filecmp.html File 22.3 KB 0644
fileformats.html File 9.14 KB 0644
fileinput.html File 24.28 KB 0644
filesys.html File 10.2 KB 0644
fl.html File 49.92 KB 0644
fm.html File 11.91 KB 0644
fnmatch.html File 14.58 KB 0644
formatter.html File 34.06 KB 0644
fpectl.html File 16.01 KB 0644
fpformat.html File 10.59 KB 0644
fractions.html File 22.61 KB 0644
framework.html File 33.34 KB 0644
frameworks.html File 7.14 KB 0644
ftplib.html File 43.99 KB 0644
functions.html File 183.14 KB 0644
functools.html File 27.17 KB 0644
future_builtins.html File 13.04 KB 0644
gc.html File 25.75 KB 0644
gdbm.html File 15.96 KB 0644
gensuitemodule.html File 11.51 KB 0644
getopt.html File 23.66 KB 0644
getpass.html File 10.65 KB 0644
gettext.html File 78.76 KB 0644
gl.html File 22.09 KB 0644
glob.html File 13.26 KB 0644
grp.html File 10.49 KB 0644
gzip.html File 18.99 KB 0644
hashlib.html File 18.2 KB 0644
heapq.html File 31.61 KB 0644
hmac.html File 10.46 KB 0644
hotshot.html File 18.65 KB 0644
htmllib.html File 25.32 KB 0644
htmlparser.html File 39.11 KB 0644
httplib.html File 62.95 KB 0644
i18n.html File 9.52 KB 0644
ic.html File 17.17 KB 0644
idle.html File 20.9 KB 0644
imageop.html File 14.76 KB 0644
imaplib.html File 51.99 KB 0644
imgfile.html File 11.71 KB 0644
imghdr.html File 11.3 KB 0644
imp.html File 34.34 KB 0644
importlib.html File 8.26 KB 0644
imputil.html File 31.81 KB 0644
index.html File 72.78 KB 0644
inspect.html File 50.71 KB 0644
internet.html File 24.87 KB 0644
intro.html File 8.93 KB 0644
io.html File 98.13 KB 0644
ipc.html File 13.41 KB 0644
itertools.html File 115.91 KB 0644
jpeg.html File 12.74 KB 0644
json.html File 67.04 KB 0644
keyword.html File 7.68 KB 0644
language.html File 11.03 KB 0644
linecache.html File 10.59 KB 0644
locale.html File 55.14 KB 0644
logging.config.html File 63.36 KB 0644
logging.handlers.html File 69.64 KB 0644
logging.html File 95.64 KB 0644
mac.html File 21.79 KB 0644
macos.html File 14.76 KB 0644
macosa.html File 12.96 KB 0644
macostools.html File 15.52 KB 0644
macpath.html File 7.76 KB 0644
mailbox.html File 156.75 KB 0644
mailcap.html File 13.21 KB 0644
markup.html File 18.77 KB 0644
marshal.html File 17.98 KB 0644
math.html File 39.24 KB 0644
md5.html File 13.97 KB 0644
mhlib.html File 21.54 KB 0644
mimetools.html File 19.25 KB 0644
mimetypes.html File 28.39 KB 0644
mimewriter.html File 15.02 KB 0644
mimify.html File 13.36 KB 0644
miniaeframe.html File 12.2 KB 0644
misc.html File 6.87 KB 0644
mm.html File 9.03 KB 0644
mmap.html File 28.36 KB 0644
modulefinder.html File 15.31 KB 0644
modules.html File 8.46 KB 0644
msilib.html File 52.43 KB 0644
msvcrt.html File 19.37 KB 0644
multifile.html File 24.3 KB 0644
multiprocessing.html File 365.71 KB 0644
mutex.html File 11.23 KB 0644
netdata.html File 16.98 KB 0644
netrc.html File 12.3 KB 0644
new.html File 12.12 KB 0644
nis.html File 10.64 KB 0644
nntplib.html File 41.92 KB 0644
numbers.html File 37.75 KB 0644
numeric.html File 13.55 KB 0644
operator.html File 82 KB 0644
optparse.html File 222.56 KB 0644
os.html File 214.25 KB 0644
os.path.html File 38.34 KB 0644
ossaudiodev.html File 41.5 KB 0644
othergui.html File 9.08 KB 0644
parser.html File 39.36 KB 0644
pdb.html File 33.96 KB 0644
persistence.html File 14.87 KB 0644
pickle.html File 102.27 KB 0644
pickletools.html File 10.63 KB 0644
pipes.html File 18.01 KB 0644
pkgutil.html File 25.11 KB 0644
platform.html File 28.37 KB 0644
plistlib.html File 17.03 KB 0644
popen2.html File 25.43 KB 0644
poplib.html File 22.32 KB 0644
posix.html File 14.41 KB 0644
posixfile.html File 19.76 KB 0644
pprint.html File 29.92 KB 0644
profile.html File 63.56 KB 0644
pty.html File 9.48 KB 0644
pwd.html File 11.43 KB 0644
py_compile.html File 11.12 KB 0644
pyclbr.html File 14.71 KB 0644
pydoc.html File 11.48 KB 0644
pyexpat.html File 71.53 KB 0644
python.html File 12.27 KB 0644
queue.html File 24.22 KB 0644
quopri.html File 11.9 KB 0644
random.html File 37.83 KB 0644
re.html File 134.74 KB 0644
readline.html File 28.24 KB 0644
repr.html File 20.43 KB 0644
resource.html File 26.48 KB 0644
restricted.html File 11.65 KB 0644
rexec.html File 37.41 KB 0644
rfc822.html File 42.22 KB 0644
rlcompleter.html File 13.51 KB 0644
robotparser.html File 12.27 KB 0644
runpy.html File 19.34 KB 0644
sched.html File 18.54 KB 0644
scrolledtext.html File 9.32 KB 0644
select.html File 39.67 KB 0644
sets.html File 36.92 KB 0644
sgi.html File 9.71 KB 0644
sgmllib.html File 30.77 KB 0644
sha.html File 12.09 KB 0644
shelve.html File 27.02 KB 0644
shlex.html File 32.1 KB 0644
shutil.html File 40.22 KB 0644
signal.html File 31.14 KB 0644
simplehttpserver.html File 18.41 KB 0644
simplexmlrpcserver.html File 31.39 KB 0644
site.html File 23.64 KB 0644
smtpd.html File 12.46 KB 0644
smtplib.html File 42.13 KB 0644
sndhdr.html File 10.02 KB 0644
socket.html File 106.34 KB 0644
socketserver.html File 59.83 KB 0644
someos.html File 15.11 KB 0644
spwd.html File 10.33 KB 0644
sqlite3.html File 139.5 KB 0644
ssl.html File 65.62 KB 0644
stat.html File 32.31 KB 0644
statvfs.html File 10.6 KB 0644
stdtypes.html File 260.4 KB 0644
string.html File 106.65 KB 0644
stringio.html File 18.81 KB 0644
stringprep.html File 16.13 KB 0644
strings.html File 14.93 KB 0644
struct.html File 40.88 KB 0644
subprocess.html File 84.91 KB 0644
sun.html File 6.84 KB 0644
sunau.html File 27.1 KB 0644
sunaudio.html File 17.79 KB 0644
symbol.html File 7.66 KB 0644
symtable.html File 22.94 KB 0644
sys.html File 98.7 KB 0644
sysconfig.html File 23.84 KB 0644
syslog.html File 17.92 KB 0644
tabnanny.html File 10.63 KB 0644
tarfile.html File 78.68 KB 0644
telnetlib.html File 25.48 KB 0644
tempfile.html File 29.42 KB 0644
termios.html File 16.01 KB 0644
test.html File 52.62 KB 0644
textwrap.html File 27.25 KB 0644
thread.html File 20.47 KB 0644
threading.html File 76.69 KB 0644
time.html File 56.93 KB 0644
timeit.html File 36.27 KB 0644
tix.html File 46.96 KB 0644
tk.html File 23.64 KB 0644
tkinter.html File 67.67 KB 0644
token.html File 19.62 KB 0644
tokenize.html File 18.45 KB 0644
trace.html File 25.54 KB 0644
traceback.html File 33.44 KB 0644
ttk.html File 101.75 KB 0644
tty.html File 9.06 KB 0644
turtle.html File 211.74 KB 0644
types.html File 27.59 KB 0644
undoc.html File 23.16 KB 0644
unicodedata.html File 18.55 KB 0644
unittest.html File 202.85 KB 0644
unix.html File 10.55 KB 0644
urllib.html File 58.68 KB 0644
urllib2.html File 100.58 KB 0644
urlparse.html File 40.41 KB 0644
user.html File 11.83 KB 0644
userdict.html File 29.73 KB 0644
uu.html File 11.03 KB 0644
uuid.html File 28.19 KB 0644
warnings.html File 46.6 KB 0644
wave.html File 22.22 KB 0644
weakref.html File 36.52 KB 0644
webbrowser.html File 23.07 KB 0644
whichdb.html File 8.85 KB 0644
windows.html File 9.33 KB 0644
winsound.html File 18.75 KB 0644
wsgiref.html File 81.04 KB 0644
xdrlib.html File 29.94 KB 0644
xml.dom.html File 89.04 KB 0644
xml.dom.minidom.html File 40.42 KB 0644
xml.dom.pulldom.html File 12.71 KB 0644
xml.etree.elementtree.html File 93.22 KB 0644
xml.html File 16.49 KB 0644
xml.sax.handler.html File 38.63 KB 0644
xml.sax.html File 20.22 KB 0644
xml.sax.reader.html File 39.09 KB 0644
xml.sax.utils.html File 14.26 KB 0644
xmlrpclib.html File 60.79 KB 0644
zipfile.html File 53.14 KB 0644
zipimport.html File 20.42 KB 0644
zlib.html File 25.46 KB 0644