0x1949 Team - FAZEMRX - MANAGER
Edit File: collections.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" /> <title>8.3. collections — High-performance container datatypes — Python 2.7.18 documentation</title> <link rel="stylesheet" type="text/css" href="../_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="../_static/classic.css" /> <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 2.7.18 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.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" /> <link rel="canonical" href="file:///usr/share/doc/python2.7/html/library/collections.html" /> <script type="text/javascript" src="../_static/copybutton.js"></script> </head><body> <div id="outdated-warning" style="padding: .5em; text-align: center; background-color: #FFBABA; color: #6A0E0E;"> This document is for an old version of Python that is <a href="https://devguide.python.org/devcycle/#end-of-life-branches">no longer supported</a>. You should install the python3 and python3-doc packages and read the <a href="file:///usr/share/doc/python3-doc/html/library/collections.html"> Python documentation for the Python3 version packaged in this release</a>. </div> <div class="related" role="navigation" aria-label="related navigation"> <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="https://www.python.org/">Python</a> »</li> <li> <a href="../index.html">Python 2.7.18 documentation</a> » </li> <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U"><span class="section-number">8. </span>Data Types</a> »</li> <li class="nav-item nav-item-this"><a href=""><span class="section-number">8.3. </span><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code> — High-performance container datatypes</a></li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="module-collections"> <span id="collections-high-performance-container-datatypes"></span><h1><span class="section-number">8.3. </span><a class="reference internal" href="#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> — High-performance container datatypes<a class="headerlink" href="#module-collections" title="Permalink to this headline">¶</a></h1> <div class="versionadded"> <p><span class="versionmodified added">New in version 2.4.</span></p> </div> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/collections.py">Lib/collections.py</a> and <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/_abcoll.py">Lib/_abcoll.py</a></p> <hr class="docutils" /> <p>This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>, <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, and <a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>.</p> <table class="docutils align-default"> <colgroup> <col style="width: 18%" /> <col style="width: 59%" /> <col style="width: 23%" /> </colgroup> <tbody> <tr class="row-odd"><td><p><a class="reference internal" href="#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code></a></p></td> <td><p>factory function for creating tuple subclasses with named fields</p></td> <td><div class="versionadded"> <p><span class="versionmodified added">New in version 2.6.</span></p> </div> </td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a></p></td> <td><p>list-like container with fast appends and pops on either end</p></td> <td><div class="versionadded"> <p><span class="versionmodified added">New in version 2.4.</span></p> </div> </td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a></p></td> <td><p>dict subclass for counting hashable objects</p></td> <td><div class="versionadded"> <p><span class="versionmodified added">New in version 2.7.</span></p> </div> </td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a></p></td> <td><p>dict subclass that remembers the order entries were added</p></td> <td><div class="versionadded"> <p><span class="versionmodified added">New in version 2.7.</span></p> </div> </td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a></p></td> <td><p>dict subclass that calls a factory function to supply missing values</p></td> <td><div class="versionadded"> <p><span class="versionmodified added">New in version 2.5.</span></p> </div> </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"><span class="std std-ref">abstract base classes</span></a> that can be used to test whether a class provides a particular interface, for example, whether it is hashable or a mapping.</p> <section id="counter-objects"> <h2><span class="section-number">8.3.1. </span><a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></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-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="c1"># Tally occurrences of words in a list</span> <span class="gp">>>> </span><span class="n">cnt</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">'red'</span><span class="p">,</span> <span class="s1">'blue'</span><span class="p">,</span> <span class="s1">'red'</span><span class="p">,</span> <span class="s1">'green'</span><span class="p">,</span> <span class="s1">'blue'</span><span class="p">,</span> <span class="s1">'blue'</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">>>> </span><span class="n">cnt</span> <span class="go">Counter({'blue': 3, 'red': 2, 'green': 1})</span> <span class="gp">>>> </span><span class="c1"># Find the ten most common words in Hamlet</span> <span class="gp">>>> </span><span class="kn">import</span> <span class="nn">re</span> <span class="gp">>>> </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="sa">r</span><span class="s1">'\w+'</span><span class="p">,</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'hamlet.txt'</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">>>> </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">[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),</span> <span class="go"> ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]</span> </pre></div> </div> <dl class="py class"> <dt class="sig sig-object py" id="collections.Counter"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">Counter</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">iterable-or-mapping</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><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"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> is a <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></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"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></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="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span> <span class="c1"># a new, empty counter</span> <span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="s1">'gallahad'</span><span class="p">)</span> <span class="c1"># a new counter from an iterable</span> <span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">({</span><span class="s1">'red'</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span> <span class="s1">'blue'</span><span class="p">:</span> <span class="mi">2</span><span class="p">})</span> <span class="c1"># a new counter from a mapping</span> <span class="gp">>>> </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="c1"># 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 <code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code>:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">([</span><span class="s1">'eggs'</span><span class="p">,</span> <span class="s1">'ham'</span><span class="p">])</span> <span class="gp">>>> </span><span class="n">c</span><span class="p">[</span><span class="s1">'bacon'</span><span class="p">]</span> <span class="c1"># 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 <code class="docutils literal notranslate"><span class="pre">del</span></code> to remove it entirely:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">c</span><span class="p">[</span><span class="s1">'sausage'</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span> <span class="c1"># counter entry with a zero count</span> <span class="gp">>>> </span><span class="k">del</span> <span class="n">c</span><span class="p">[</span><span class="s1">'sausage'</span><span class="p">]</span> <span class="c1"># del actually removes the entry</span> </pre></div> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 2.7.</span></p> </div> <p>Counter objects support three methods beyond those available for all dictionaries:</p> <dl class="py method"> <dt class="sig sig-object py" id="collections.Counter.elements"> <span class="sig-name descname"><span class="pre">elements</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><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’s count is less than one, <a class="reference internal" href="#collections.Counter.elements" title="collections.Counter.elements"><code class="xref py py-meth docutils literal notranslate"><span class="pre">elements()</span></code></a> will ignore it.</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </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">>>> </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">['a', 'a', 'a', 'a', 'b', 'b']</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.Counter.most_common"> <span class="sig-name descname"><span class="pre">most_common</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">n</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><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 omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="#collections.Counter.most_common" title="collections.Counter.most_common"><code class="xref py py-func docutils literal notranslate"><span class="pre">most_common()</span></code></a> returns <em>all</em> elements in the counter. Elements with equal counts are ordered arbitrarily:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Counter</span><span class="p">(</span><span class="s1">'abracadabra'</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">[('a', 5), ('r', 2), ('b', 2)]</span> </pre></div> </div> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.Counter.subtract"> <span class="sig-name descname"><span class="pre">subtract</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">iterable-or-mapping</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><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"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.update()</span></code></a> but subtracts counts instead of replacing them. Both inputs and outputs may be zero or negative.</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </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">>>> </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">>>> </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">>>> </span><span class="n">c</span> <span class="go">Counter({'a': 3, 'b': 0, 'c': -3, 'd': -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"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects except for two which work differently for counters.</p> <dl class="py method"> <dt class="sig sig-object py" id="collections.Counter.fromkeys"> <span class="sig-name descname"><span class="pre">fromkeys</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">iterable</span></span></em><span class="sig-paren">)</span><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"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.Counter.update"> <span class="sig-name descname"><span class="pre">update</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">iterable-or-mapping</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><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"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.update()</span></code></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 <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> pairs.</p> </dd></dl> </dd></dl> <p>Common patterns for working with <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><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="c1"># 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="c1"># reset all counts</span> <span class="nb">list</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="c1"># list unique elements</span> <span class="nb">set</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="c1"># 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="c1"># 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="c1"># 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="c1"># 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="o">-</span><span class="mi">1</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="c1"># 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="c1"># 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"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></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="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </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">>>> </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">>>> </span><span class="n">c</span> <span class="o">+</span> <span class="n">d</span> <span class="c1"># add two counters together: c[x] + d[x]</span> <span class="go">Counter({'a': 4, 'b': 3})</span> <span class="gp">>>> </span><span class="n">c</span> <span class="o">-</span> <span class="n">d</span> <span class="c1"># subtract (keeping only positive counts)</span> <span class="go">Counter({'a': 2})</span> <span class="gp">>>> </span><span class="n">c</span> <span class="o">&</span> <span class="n">d</span> <span class="c1"># intersection: min(c[x], d[x])</span> <span class="go">Counter({'a': 1, 'b': 1})</span> <span class="gp">>>> </span><span class="n">c</span> <span class="o">|</span> <span class="n">d</span> <span class="c1"># union: max(c[x], d[x])</span> <span class="go">Counter({'a': 3, 'b': 2})</span> </pre></div> </div> <div class="admonition note"> <p class="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="simple"> <li><p>The <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></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.</p></li> <li><p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">most_common()</span></code> method requires only that the values be orderable.</p></li> <li><p>For in-place operations such as <code class="docutils literal notranslate"><span class="pre">c[key]</span> <span class="pre">+=</span> <span class="pre">1</span></code>, 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 <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">subtract()</span></code> which allow negative and zero values for both inputs and outputs.</p></li> <li><p>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.</p></li> <li><p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">elements()</span></code> method requires integer counts. It ignores zero and negative counts.</p></li> </ul> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <ul> <li><p><a class="reference external" href="https://code.activestate.com/recipes/576611/">Counter class</a> adapted for Python 2.5 and an early <a class="reference external" href="https://code.activestate.com/recipes/259174/">Bag recipe</a> for Python 2.4.</p></li> <li><p><a class="reference external" href="https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html">Bag class</a> in Smalltalk.</p></li> <li><p>Wikipedia entry for <a class="reference external" href="https://en.wikipedia.org/wiki/Multiset">Multisets</a>.</p></li> <li><p><a class="reference external" href="http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm">C++ multisets</a> tutorial with examples.</p></li> <li><p>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>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"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.combinations_with_replacement()</span></code></a>.</p> <blockquote> <div><p>map(Counter, combinations_with_replacement(‘ABC’, 2)) –> AA AB AC BB BC CC</p> </div></blockquote> </li> </ul> </div> </section> <section id="deque-objects"> <h2><span class="section-number">8.3.2. </span><a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> objects<a class="headerlink" href="#deque-objects" title="Permalink to this headline">¶</a></h2> <dl class="py class"> <dt class="sig sig-object py" id="collections.deque"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">deque</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">iterable</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">maxlen</span></span></em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><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"><code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code></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 “deck” and is short for “double-ended queue”). 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 <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for <code class="docutils literal notranslate"><span class="pre">pop(0)</span></code> and <code class="docutils literal notranslate"><span class="pre">insert(0,</span> <span class="pre">v)</span></code> operations which change both the size and position of the underlying data representation.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 2.4.</span></p> </div> <p>If <em>maxlen</em> is not specified or is <code class="docutils literal notranslate"><span class="pre">None</span></code>, 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 <code class="docutils literal notranslate"><span class="pre">tail</span></code> 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> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 2.6: </span>Added <em>maxlen</em> parameter.</p> </div> <p>Deque objects support the following methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.append"> <span class="sig-name descname"><span class="pre">append</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">x</span></span></em><span class="sig-paren">)</span><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="py method"> <dt class="sig sig-object py" id="collections.deque.appendleft"> <span class="sig-name descname"><span class="pre">appendleft</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">x</span></span></em><span class="sig-paren">)</span><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="py method"> <dt class="sig sig-object py" id="collections.deque.clear"> <span class="sig-name descname"><span class="pre">clear</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><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="py method"> <dt class="sig sig-object py" id="collections.deque.count"> <span class="sig-name descname"><span class="pre">count</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">x</span></span></em><span class="sig-paren">)</span><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> <div class="versionadded"> <p><span class="versionmodified added">New in version 2.7.</span></p> </div> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.extend"> <span class="sig-name descname"><span class="pre">extend</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">iterable</span></span></em><span class="sig-paren">)</span><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="py method"> <dt class="sig sig-object py" id="collections.deque.extendleft"> <span class="sig-name descname"><span class="pre">extendleft</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">iterable</span></span></em><span class="sig-paren">)</span><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="py method"> <dt class="sig sig-object py" id="collections.deque.pop"> <span class="sig-name descname"><span class="pre">pop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><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 <code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code>.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.popleft"> <span class="sig-name descname"><span class="pre">popleft</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><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 <code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code>.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.remove"> <span class="sig-name descname"><span class="pre">remove</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.remove" title="Permalink to this definition">¶</a></dt> <dd><p>Remove the first occurrence of <em>value</em>. If not found, raises a <code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 2.5.</span></p> </div> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.reverse"> <span class="sig-name descname"><span class="pre">reverse</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><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 <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 2.7.</span></p> </div> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.rotate"> <span class="sig-name descname"><span class="pre">rotate</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">n</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</span></span></em><span class="sig-paren">)</span><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.</p> <p>When the deque is not empty, rotating one step to the right is equivalent to <code class="docutils literal notranslate"><span class="pre">d.appendleft(d.pop())</span></code>, and rotating one step to the left is equivalent to <code class="docutils literal notranslate"><span class="pre">d.append(d.popleft())</span></code>.</p> </dd></dl> <p>Deque objects also provide one read-only attribute:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="collections.deque.maxlen"> <span class="sig-name descname"><span class="pre">maxlen</span></span><a class="headerlink" href="#collections.deque.maxlen" title="Permalink to this definition">¶</a></dt> <dd><p>Maximum size of a deque or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unbounded.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 2.7.</span></p> </div> </dd></dl> </dd></dl> <p>In addition to the above, deques support iteration, pickling, <code class="docutils literal notranslate"><span class="pre">len(d)</span></code>, <code class="docutils literal notranslate"><span class="pre">reversed(d)</span></code>, <code class="docutils literal notranslate"><span class="pre">copy.copy(d)</span></code>, <code class="docutils literal notranslate"><span class="pre">copy.deepcopy(d)</span></code>, membership testing with the <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> operator, and subscript references such as <code class="docutils literal notranslate"><span class="pre">d[-1]</span></code>. 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-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">deque</span> <span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="s1">'ghi'</span><span class="p">)</span> <span class="c1"># make a new deque with three items</span> <span class="gp">>>> </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="c1"># iterate over the deque's elements</span> <span class="gp">... </span> <span class="nb">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">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">'j'</span><span class="p">)</span> <span class="c1"># add a new entry to the right side</span> <span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">appendleft</span><span class="p">(</span><span class="s1">'f'</span><span class="p">)</span> <span class="c1"># add a new entry to the left side</span> <span class="gp">>>> </span><span class="n">d</span> <span class="c1"># show the representation of the deque</span> <span class="go">deque(['f', 'g', 'h', 'i', 'j'])</span> <span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span> <span class="c1"># return and remove the rightmost item</span> <span class="go">'j'</span> <span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span> <span class="c1"># return and remove the leftmost item</span> <span class="go">'f'</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="p">)</span> <span class="c1"># list the contents of the deque</span> <span class="go">['g', 'h', 'i']</span> <span class="gp">>>> </span><span class="n">d</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="c1"># peek at leftmost item</span> <span class="go">'g'</span> <span class="gp">>>> </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="c1"># peek at rightmost item</span> <span class="go">'i'</span> <span class="gp">>>> </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="c1"># list the contents of a deque in reverse</span> <span class="go">['i', 'h', 'g']</span> <span class="gp">>>> </span><span class="s1">'h'</span> <span class="ow">in</span> <span class="n">d</span> <span class="c1"># search the deque</span> <span class="go">True</span> <span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="s1">'jkl'</span><span class="p">)</span> <span class="c1"># add multiple elements at once</span> <span class="gp">>>> </span><span class="n">d</span> <span class="go">deque(['g', 'h', 'i', 'j', 'k', 'l'])</span> <span class="gp">>>> </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="c1"># right rotation</span> <span class="gp">>>> </span><span class="n">d</span> <span class="go">deque(['l', 'g', 'h', 'i', 'j', 'k'])</span> <span class="gp">>>> </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="c1"># left rotation</span> <span class="gp">>>> </span><span class="n">d</span> <span class="go">deque(['g', 'h', 'i', 'j', 'k', 'l'])</span> <span class="gp">>>> </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="c1"># make a new deque in reverse order</span> <span class="go">deque(['l', 'k', 'j', 'i', 'h', 'g'])</span> <span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span> <span class="c1"># empty the deque</span> <span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span> <span class="c1"># cannot pop from an empty deque</span> <span class="gt">Traceback (most recent call last):</span> File <span class="nb">"<pyshell#6>"</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">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">extendleft</span><span class="p">(</span><span class="s1">'abc'</span><span class="p">)</span> <span class="c1"># extendleft() reverses the input order</span> <span class="gp">>>> </span><span class="n">d</span> <span class="go">deque(['c', 'b', 'a'])</span> </pre></div> </div> <section id="deque-recipes"> <h3><span class="section-number">8.3.2.1. </span><a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></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 <code class="docutils literal notranslate"><span class="pre">tail</span></code> filter in Unix:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><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="s1">'Return the last n lines of a file'</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-default notranslate"><div class="highlight"><pre><span></span><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="c1"># moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0</span> <span class="c1"># 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 <code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code> method provides a way to implement <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> slicing and deletion. For example, a pure Python implementation of <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">d[n]</span></code> relies on the <code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code> method to position elements to be popped:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><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"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> slicing, use a similar approach applying <code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code> to bring a target element to the left side of the deque. Remove old entries with <code class="xref py py-meth docutils literal notranslate"><span class="pre">popleft()</span></code>, add new entries with <code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code>, and then reverse the rotation. With minor variations on that approach, it is easy to implement Forth style stack manipulations such as <code class="docutils literal notranslate"><span class="pre">dup</span></code>, <code class="docutils literal notranslate"><span class="pre">drop</span></code>, <code class="docutils literal notranslate"><span class="pre">swap</span></code>, <code class="docutils literal notranslate"><span class="pre">over</span></code>, <code class="docutils literal notranslate"><span class="pre">pick</span></code>, <code class="docutils literal notranslate"><span class="pre">rot</span></code>, and <code class="docutils literal notranslate"><span class="pre">roll</span></code>.</p> </section> </section> <section id="defaultdict-objects"> <h2><span class="section-number">8.3.3. </span><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> objects<a class="headerlink" href="#defaultdict-objects" title="Permalink to this headline">¶</a></h2> <dl class="py class"> <dt class="sig sig-object py" id="collections.defaultdict"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">defaultdict</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">default_factory</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">...</span></span></em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><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"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> is a subclass of the built-in <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></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"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></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"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> attribute; it defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>. All remaining arguments are treated the same as if they were passed to the <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> constructor, including keyword arguments.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 2.5.</span></p> </div> <p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> objects support the following method in addition to the standard <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> operations:</p> <dl class="py method"> <dt class="sig sig-object py" id="collections.defaultdict.__missing__"> <span class="sig-name descname"><span class="pre">__missing__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">key</span></span></em><span class="sig-paren">)</span><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"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> attribute is <code class="docutils literal notranslate"><span class="pre">None</span></code>, this raises a <code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code> 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"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, 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"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> raises an exception this exception is propagated unchanged.</p> <p>This method is called by the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code> method of the <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> class when the requested key is not found; whatever it returns or raises is then returned or raised by <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code>.</p> <p>Note that <a class="reference internal" href="#collections.defaultdict.__missing__" title="collections.defaultdict.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> is <em>not</em> called for any operations besides <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code>. This means that <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code> will, like normal dictionaries, return <code class="docutils literal notranslate"><span class="pre">None</span></code> as a default rather than using <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a>.</p> </dd></dl> <p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> objects support the following instance variable:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="collections.defaultdict.default_factory"> <span class="sig-name descname"><span class="pre">default_factory</span></span><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__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> method; it is initialized from the first argument to the constructor, if present, or to <code class="docutils literal notranslate"><span class="pre">None</span></code>, if absent.</p> </dd></dl> </dd></dl> <section id="defaultdict-examples"> <h3><span class="section-number">8.3.3.1. </span><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> Examples<a class="headerlink" href="#defaultdict-examples" title="Permalink to this headline">¶</a></h3> <p>Using <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code>, it is easy to group a sequence of key-value pairs into a dictionary of lists:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">'yellow'</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">'blue'</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">'yellow'</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s1">'blue'</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="s1">'red'</span><span class="p">,</span> <span class="mi">1</span><span class="p">)]</span> <span class="gp">>>> </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">>>> </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">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span> <span class="go">[('blue', [2, 4]), ('red', [1]), ('yellow', [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 <code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code> function which returns an empty <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.append()</span></code> 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 <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.append()</span></code> 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"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.setdefault()</span></code></a>:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="p">{}</span> <span class="gp">>>> </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">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span> <span class="go">[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]</span> </pre></div> </div> <p>Setting the <code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code> to <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> makes the <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> useful for counting (like a bag or multiset in other languages):</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="s1">'mississippi'</span> <span class="gp">>>> </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">>>> </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">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span> <span class="go">[('i', 4), ('p', 2), ('s', 4), ('m', 1)]</span> </pre></div> </div> <p>When a letter is first encountered, it is missing from the mapping, so the <code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code> function calls <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></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"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></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"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.repeat()</span></code></a> which can supply any constant value (not just zero):</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </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">>>> </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="s1">'<missing>'</span><span class="p">))</span> <span class="gp">>>> </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="s1">'John'</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">'ran'</span><span class="p">)</span> <span class="gp">>>> </span><span class="s1">'</span><span class="si">%(name)s</span><span class="s1"> </span><span class="si">%(action)s</span><span class="s1"> to </span><span class="si">%(object)s</span><span class="s1">'</span> <span class="o">%</span> <span class="n">d</span> <span class="go">'John ran to <missing>'</span> </pre></div> </div> <p>Setting the <code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code> to <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> makes the <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> useful for building a dictionary of sets:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">'red'</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">'blue'</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">'red'</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s1">'blue'</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="s1">'red'</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">'blue'</span><span class="p">,</span> <span class="mi">4</span><span class="p">)]</span> <span class="gp">>>> </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">>>> </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">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span> <span class="go">[('blue', set([2, 4])), ('red', set([1, 3]))]</span> </pre></div> </div> </section> </section> <section id="namedtuple-factory-function-for-tuples-with-named-fields"> <h2><span class="section-number">8.3.4. </span><a class="reference internal" href="#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code></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="py function"> <dt class="sig sig-object py" id="collections.namedtuple"> <span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">namedtuple</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">typename</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">field_names</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">verbose=False</span></span></em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">rename=False</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><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 <code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code> method which lists the tuple contents in a <code class="docutils literal notranslate"><span class="pre">name=value</span></code> format.</p> <p>The <em>field_names</em> are a sequence of strings such as <code class="docutils literal notranslate"><span class="pre">['x',</span> <span class="pre">'y']</span></code>. Alternatively, <em>field_names</em> can be a single string with each fieldname separated by whitespace and/or commas, for example <code class="docutils literal notranslate"><span class="pre">'x</span> <span class="pre">y'</span></code> or <code class="docutils literal notranslate"><span class="pre">'x,</span> <span class="pre">y'</span></code>.</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."><code class="xref py py-mod docutils literal notranslate"><span class="pre">keyword</span></code></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, <code class="docutils literal notranslate"><span class="pre">['abc',</span> <span class="pre">'def',</span> <span class="pre">'ghi',</span> <span class="pre">'abc']</span></code> is converted to <code class="docutils literal notranslate"><span class="pre">['abc',</span> <span class="pre">'_1',</span> <span class="pre">'ghi',</span> <span class="pre">'_3']</span></code>, eliminating the keyword <code class="docutils literal notranslate"><span class="pre">def</span></code> and the duplicate fieldname <code class="docutils literal notranslate"><span class="pre">abc</span></code>.</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> <div class="versionadded"> <p><span class="versionmodified added">New in version 2.6.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 2.7: </span>added support for <em>rename</em>.</p> </div> </dd></dl> <p>Example:</p> <div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Point</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Point'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'x'</span><span class="p">,</span> <span class="s1">'y'</span><span class="p">],</span> <span class="n">verbose</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="go">class Point(tuple):</span> <span class="go"> 'Point(x, y)'</span> <span class="go"> __slots__ = ()</span> <span class="go"> _fields = ('x', 'y')</span> <span class="go"> def __new__(_cls, x, y):</span> <span class="go"> 'Create new instance of Point(x, y)'</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"> 'Make a new Point object from a sequence or iterable'</span> <span class="go"> result = new(cls, iterable)</span> <span class="go"> if len(result) != 2:</span> <span class="go"> raise TypeError('Expected 2 arguments, got %d' % len(result))</span> <span class="go"> return result</span> <span class="go"> def __repr__(self):</span> <span class="go"> 'Return a nicely formatted representation string'</span> <span class="go"> return 'Point(x=%r, y=%r)' % self</span> <span class="go"> def _asdict(self):</span> <span class="go"> 'Return a new OrderedDict which maps field names to their values'</span> <span class="go"> return OrderedDict(zip(self._fields, self))</span> <span class="go"> def _replace(_self, **kwds):</span> <span class="go"> 'Return a new Point object replacing specified fields with new values'</span> <span class="go"> result = _self._make(map(kwds.pop, ('x', 'y'), _self))</span> <span class="go"> if kwds:</span> <span class="go"> raise ValueError('Got unexpected field names: %r' % kwds.keys())</span> <span class="go"> return result</span> <span class="go"> def __getnewargs__(self):</span> <span class="go"> 'Return self as a plain tuple. Used by copy and pickle.'</span> <span class="go"> return tuple(self)</span> <span class="go"> __dict__ = _property(_asdict)</span> <span class="go"> def __getstate__(self):</span> <span class="go"> 'Exclude the OrderedDict from pickling'</span> <span class="go"> pass</span> <span class="go"> x = _property(_itemgetter(0), doc='Alias for field number 0')</span> <span class="go"> y = _property(_itemgetter(1), doc='Alias for field number 1')</span> <span class="gp">>>> </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="c1"># instantiate with positional or keyword arguments</span> <span class="gp">>>> </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="c1"># indexable like the plain tuple (11, 22)</span> <span class="go">33</span> <span class="gp">>>> </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="c1"># unpack like a regular tuple</span> <span class="gp">>>> </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="go">(11, 22)</span> <span class="gp">>>> </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="c1"># fields also accessible by name</span> <span class="go">33</span> <span class="gp">>>> </span><span class="n">p</span> <span class="c1"># 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."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> or <a class="reference internal" href="sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> modules:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">EmployeeRecord</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'EmployeeRecord'</span><span class="p">,</span> <span class="s1">'name, age, title, department, paygrade'</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="s2">"employees.csv"</span><span class="p">,</span> <span class="s2">"rb"</span><span class="p">))):</span> <span class="nb">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="s1">'/companydata'</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="s1">'SELECT name, age, title, department, paygrade FROM employees'</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="nb">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="py method"> <dt class="sig sig-object py" id="collections.somenamedtuple._make"> <em class="property"><span class="pre">classmethod</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">somenamedtuple.</span></span><span class="sig-name descname"><span class="pre">_make</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">iterable</span></span></em><span class="sig-paren">)</span><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-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </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">>>> </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="py method"> <dt class="sig sig-object py" id="collections.somenamedtuple._asdict"> <span class="sig-prename descclassname"><span class="pre">somenamedtuple.</span></span><span class="sig-name descname"><span class="pre">_asdict</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><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"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> which maps field names to their corresponding values:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </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">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">_asdict</span><span class="p">()</span> <span class="go">OrderedDict([('x', 11), ('y', 22)])</span> </pre></div> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 2.7: </span>Returns an <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> instead of a regular <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.</p> </div> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.somenamedtuple._replace"> <span class="sig-prename descclassname"><span class="pre">somenamedtuple.</span></span><span class="sig-name descname"><span class="pre">_replace</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwargs</span></span></em><span class="sig-paren">)</span><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-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </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">>>> </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">>>> </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="gp">... </span> <span class="n">inventory</span><span class="p">[</span><span class="n">partnum</span><span class="p">]</span> <span class="o">=</span> <span class="n">record</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">price</span><span class="o">=</span><span class="n">newprices</span><span class="p">[</span><span class="n">partnum</span><span class="p">],</span> <span class="n">timestamp</span><span class="o">=</span><span class="n">time</span><span class="o">.</span><span class="n">now</span><span class="p">())</span> </pre></div> </div> </dd></dl> <dl class="py attribute"> <dt class="sig sig-object py" id="collections.somenamedtuple._fields"> <span class="sig-prename descclassname"><span class="pre">somenamedtuple.</span></span><span class="sig-name descname"><span class="pre">_fields</span></span><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-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">_fields</span> <span class="c1"># view the field names</span> <span class="go">('x', 'y')</span> <span class="gp">>>> </span><span class="n">Color</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Color'</span><span class="p">,</span> <span class="s1">'red green blue'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">Pixel</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Pixel'</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">>>> </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"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> function:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">getattr</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="s1">'x'</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"><span class="std std-ref">Unpacking Argument Lists</span></a>):</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'x'</span><span class="p">:</span> <span class="mi">11</span><span class="p">,</span> <span class="s1">'y'</span><span class="p">:</span> <span class="mi">22</span><span class="p">}</span> <span class="gp">>>> </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="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </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="s1">'Point'</span><span class="p">,</span> <span class="s1">'x y'</span><span class="p">)):</span> <span class="gp">... </span> <span class="vm">__slots__</span> <span class="o">=</span> <span class="p">()</span> <span class="gp">... </span> <span class="nd">@property</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">hypot</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span> <span class="o">**</span> <span class="mi">2</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">**</span> <span class="mi">2</span><span class="p">)</span> <span class="o">**</span> <span class="mf">0.5</span> <span class="gp">... </span> <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="s1">'Point: x=</span><span class="si">%6.3f</span><span class="s1"> y=</span><span class="si">%6.3f</span><span class="s1"> hypot=</span><span class="si">%6.3f</span><span class="s1">'</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">hypot</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </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="gp">... </span> <span class="nb">print</span> <span class="n">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 <code class="docutils literal notranslate"><span class="pre">__slots__</span></code> 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 <code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields</span></code> attribute:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Point3D</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Point3D'</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="s1">'z'</span><span class="p">,))</span> </pre></div> </div> <p>Default values can be implemented by using <code class="xref py py-meth docutils literal notranslate"><span class="pre">_replace()</span></code> to customize a prototype instance:</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Account</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Account'</span><span class="p">,</span> <span class="s1">'owner balance transaction_count'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">default_account</span> <span class="o">=</span> <span class="n">Account</span><span class="p">(</span><span class="s1">'<owner name>'</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">>>> </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="s1">'John'</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="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Status</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Status'</span><span class="p">,</span> <span class="s1">'open pending closed'</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">>>> </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">>>> </span><span class="k">class</span> <span class="nc">Status</span><span class="p">:</span> <span class="gp">... </span> <span class="nb">open</span><span class="p">,</span> <span class="n">pending</span><span class="p">,</span> <span class="n">closed</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> </pre></div> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference external" href="https://code.activestate.com/recipes/500261/">Named tuple recipe</a> adapted for Python 2.4.</p> </div> </section> <section id="ordereddict-objects"> <h2><span class="section-number">8.3.5. </span><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></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="py class"> <dt class="sig sig-object py" id="collections.OrderedDict"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">OrderedDict</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">items</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><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"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></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> <div class="versionadded"> <p><span class="versionmodified added">New in version 2.7.</span></p> </div> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.OrderedDict.popitem"> <span class="sig-prename descclassname"><span class="pre">OrderedDict.</span></span><span class="sig-name descname"><span class="pre">popitem</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">last</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em><span class="sig-paren">)</span><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"><code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code></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"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a>.</p> <p>Equality tests between <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects are order-sensitive and are implemented as <code class="docutils literal notranslate"><span class="pre">list(od1.items())==list(od2.items())</span></code>. Equality tests between <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects and other <a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a> objects are order-insensitive like regular dictionaries. This allows <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects to be substituted anywhere a regular dictionary is used.</p> <p>The <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> constructor and <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> method both accept keyword arguments, but their order is lost because Python’s function call semantics pass-in keyword arguments using a regular unordered dictionary.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference external" href="https://code.activestate.com/recipes/576693/">Equivalent OrderedDict recipe</a> that runs on Python 2.4 or later.</p> </div> <section id="ordereddict-examples-and-recipes"> <h3><span class="section-number">8.3.5.1. </span><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></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 conjunction with sorting to make a sorted dictionary:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="c1"># regular unsorted dictionary</span> <span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'banana'</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">'apple'</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span> <span class="s1">'pear'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">'orange'</span><span class="p">:</span> <span class="mi">2</span><span class="p">}</span> <span class="gp">>>> </span><span class="c1"># dictionary sorted by key</span> <span class="gp">>>> </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([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])</span> <span class="gp">>>> </span><span class="c1"># dictionary sorted by value</span> <span class="gp">>>> </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([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])</span> <span class="gp">>>> </span><span class="c1"># dictionary sorted by length of the key string</span> <span class="gp">>>> </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([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 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-default notranslate"><div class="highlight"><pre><span></span><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="s1">'Store items in the order the keys were last added'</span> <span class="k">def</span> <span class="fm">__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="fm">__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"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> class so that the counter remembers the order elements are first encountered:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><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="s1">'Counter that remembers the order elements are first encountered'</span> <span class="k">def</span> <span class="fm">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="s1">'</span><span class="si">%s</span><span class="s1">(</span><span class="si">%r</span><span class="s1">)'</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__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="vm">__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> </section> </section> <section id="collections-abstract-base-classes"> <span id="id1"></span><h2><span class="section-number">8.3.6. </span>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"><span class="xref std std-term">ABCs</span></a>:</p> <table class="docutils align-default"> <colgroup> <col style="width: 21%" /> <col style="width: 18%" /> <col style="width: 18%" /> <col style="width: 43%" /> </colgroup> <thead> <tr class="row-odd"><th class="head"><p>ABC</p></th> <th class="head"><p>Inherits from</p></th> <th class="head"><p>Abstract Methods</p></th> <th class="head"><p>Mixin Methods</p></th> </tr> </thead> <tbody> <tr class="row-even"><td><p><a class="reference internal" href="#collections.Container" title="collections.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code></a></p></td> <td></td> <td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code></p></td> <td></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="#collections.Hashable" title="collections.Hashable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Hashable</span></code></a></p></td> <td></td> <td><p><code class="docutils literal notranslate"><span class="pre">__hash__</span></code></p></td> <td></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a></p></td> <td></td> <td><p><code class="docutils literal notranslate"><span class="pre">__iter__</span></code></p></td> <td></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="#collections.Iterator" title="collections.Iterator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterator</span></code></a></p></td> <td><p><a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a></p></td> <td><p><code class="docutils literal notranslate"><span class="pre">next</span></code></p></td> <td><p><code class="docutils literal notranslate"><span class="pre">__iter__</span></code></p></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a></p></td> <td></td> <td><p><code class="docutils literal notranslate"><span class="pre">__len__</span></code></p></td> <td></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="#collections.Callable" title="collections.Callable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Callable</span></code></a></p></td> <td></td> <td><p><code class="docutils literal notranslate"><span class="pre">__call__</span></code></p></td> <td></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="#collections.Sequence" title="collections.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sequence</span></code></a></p></td> <td><p><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a>, <a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a>, <a class="reference internal" href="#collections.Container" title="collections.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code></a></p></td> <td><p><code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>, <code class="docutils literal notranslate"><span class="pre">__len__</span></code></p></td> <td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>, <code class="docutils literal notranslate"><span class="pre">__iter__</span></code>, <code class="docutils literal notranslate"><span class="pre">__reversed__</span></code>, <code class="docutils literal notranslate"><span class="pre">index</span></code>, and <code class="docutils literal notranslate"><span class="pre">count</span></code></p></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="#collections.MutableSequence" title="collections.MutableSequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableSequence</span></code></a></p></td> <td><p><a class="reference internal" href="#collections.Sequence" title="collections.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sequence</span></code></a></p></td> <td><p><code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>, <code class="docutils literal notranslate"><span class="pre">__setitem__</span></code>, <code class="docutils literal notranslate"><span class="pre">__delitem__</span></code>, <code class="docutils literal notranslate"><span class="pre">__len__</span></code>, <code class="docutils literal notranslate"><span class="pre">insert</span></code></p></td> <td><p>Inherited <a class="reference internal" href="#collections.Sequence" title="collections.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sequence</span></code></a> methods and <code class="docutils literal notranslate"><span class="pre">append</span></code>, <code class="docutils literal notranslate"><span class="pre">reverse</span></code>, <code class="docutils literal notranslate"><span class="pre">extend</span></code>, <code class="docutils literal notranslate"><span class="pre">pop</span></code>, <code class="docutils literal notranslate"><span class="pre">remove</span></code>, and <code class="docutils literal notranslate"><span class="pre">__iadd__</span></code></p></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a></p></td> <td><p><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a>, <a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a>, <a class="reference internal" href="#collections.Container" title="collections.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code></a></p></td> <td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>, <code class="docutils literal notranslate"><span class="pre">__iter__</span></code>, <code class="docutils literal notranslate"><span class="pre">__len__</span></code></p></td> <td><p><code class="docutils literal notranslate"><span class="pre">__le__</span></code>, <code class="docutils literal notranslate"><span class="pre">__lt__</span></code>, <code class="docutils literal notranslate"><span class="pre">__eq__</span></code>, <code class="docutils literal notranslate"><span class="pre">__ne__</span></code>, <code class="docutils literal notranslate"><span class="pre">__gt__</span></code>, <code class="docutils literal notranslate"><span class="pre">__ge__</span></code>, <code class="docutils literal notranslate"><span class="pre">__and__</span></code>, <code class="docutils literal notranslate"><span class="pre">__or__</span></code>, <code class="docutils literal notranslate"><span class="pre">__sub__</span></code>, <code class="docutils literal notranslate"><span class="pre">__xor__</span></code>, and <code class="docutils literal notranslate"><span class="pre">isdisjoint</span></code></p></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="#collections.MutableSet" title="collections.MutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableSet</span></code></a></p></td> <td><p><a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a></p></td> <td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>, <code class="docutils literal notranslate"><span class="pre">__iter__</span></code>, <code class="docutils literal notranslate"><span class="pre">__len__</span></code>, <code class="docutils literal notranslate"><span class="pre">add</span></code>, <code class="docutils literal notranslate"><span class="pre">discard</span></code></p></td> <td><p>Inherited <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> methods and <code class="docutils literal notranslate"><span class="pre">clear</span></code>, <code class="docutils literal notranslate"><span class="pre">pop</span></code>, <code class="docutils literal notranslate"><span class="pre">remove</span></code>, <code class="docutils literal notranslate"><span class="pre">__ior__</span></code>, <code class="docutils literal notranslate"><span class="pre">__iand__</span></code>, <code class="docutils literal notranslate"><span class="pre">__ixor__</span></code>, and <code class="docutils literal notranslate"><span class="pre">__isub__</span></code></p></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a></p></td> <td><p><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a>, <a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a>, <a class="reference internal" href="#collections.Container" title="collections.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code></a></p></td> <td><p><code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>, <code class="docutils literal notranslate"><span class="pre">__iter__</span></code>, <code class="docutils literal notranslate"><span class="pre">__len__</span></code></p></td> <td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>, <code class="docutils literal notranslate"><span class="pre">keys</span></code>, <code class="docutils literal notranslate"><span class="pre">items</span></code>, <code class="docutils literal notranslate"><span class="pre">values</span></code>, <code class="docutils literal notranslate"><span class="pre">get</span></code>, <code class="docutils literal notranslate"><span class="pre">__eq__</span></code>, and <code class="docutils literal notranslate"><span class="pre">__ne__</span></code></p></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="#collections.MutableMapping" title="collections.MutableMapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableMapping</span></code></a></p></td> <td><p><a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a></p></td> <td><p><code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>, <code class="docutils literal notranslate"><span class="pre">__setitem__</span></code>, <code class="docutils literal notranslate"><span class="pre">__delitem__</span></code>, <code class="docutils literal notranslate"><span class="pre">__iter__</span></code>, <code class="docutils literal notranslate"><span class="pre">__len__</span></code></p></td> <td><p>Inherited <a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a> methods and <code class="docutils literal notranslate"><span class="pre">pop</span></code>, <code class="docutils literal notranslate"><span class="pre">popitem</span></code>, <code class="docutils literal notranslate"><span class="pre">clear</span></code>, <code class="docutils literal notranslate"><span class="pre">update</span></code>, and <code class="docutils literal notranslate"><span class="pre">setdefault</span></code></p></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><code class="xref py py-class docutils literal notranslate"><span class="pre">MappingView</span></code></a></p></td> <td><p><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a></p></td> <td></td> <td><p><code class="docutils literal notranslate"><span class="pre">__len__</span></code></p></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="#collections.ItemsView" title="collections.ItemsView"><code class="xref py py-class docutils literal notranslate"><span class="pre">ItemsView</span></code></a></p></td> <td><p><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><code class="xref py py-class docutils literal notranslate"><span class="pre">MappingView</span></code></a>, <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a></p></td> <td></td> <td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>, <code class="docutils literal notranslate"><span class="pre">__iter__</span></code></p></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="#collections.KeysView" title="collections.KeysView"><code class="xref py py-class docutils literal notranslate"><span class="pre">KeysView</span></code></a></p></td> <td><p><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><code class="xref py py-class docutils literal notranslate"><span class="pre">MappingView</span></code></a>, <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a></p></td> <td></td> <td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>, <code class="docutils literal notranslate"><span class="pre">__iter__</span></code></p></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="#collections.ValuesView" title="collections.ValuesView"><code class="xref py py-class docutils literal notranslate"><span class="pre">ValuesView</span></code></a></p></td> <td><p><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><code class="xref py py-class docutils literal notranslate"><span class="pre">MappingView</span></code></a></p></td> <td></td> <td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>, <code class="docutils literal notranslate"><span class="pre">__iter__</span></code></p></td> </tr> </tbody> </table> <dl class="py class"> <dt class="sig sig-object py" id="collections.Container"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">Container</span></span><a class="headerlink" href="#collections.Container" title="Permalink to this definition">¶</a></dt> <dt class="sig sig-object py" id="collections.Hashable"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">Hashable</span></span><a class="headerlink" href="#collections.Hashable" title="Permalink to this definition">¶</a></dt> <dt class="sig sig-object py" id="collections.Sized"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">Sized</span></span><a class="headerlink" href="#collections.Sized" title="Permalink to this definition">¶</a></dt> <dt class="sig sig-object py" id="collections.Callable"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">Callable</span></span><a class="headerlink" href="#collections.Callable" title="Permalink to this definition">¶</a></dt> <dd><p>ABCs for classes that provide respectively the methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code>.</p> </dd></dl> <dl class="py class"> <dt class="sig sig-object py" id="collections.Iterable"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">Iterable</span></span><a class="headerlink" href="#collections.Iterable" title="Permalink to this definition">¶</a></dt> <dd><p>ABC for classes that provide the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code> method. See also the definition of <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a>.</p> </dd></dl> <dl class="py class"> <dt class="sig sig-object py" id="collections.Iterator"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">Iterator</span></span><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="stdtypes.html#iterator.__iter__" title="iterator.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> and <a class="reference internal" href="stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> methods. See also the definition of <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>.</p> </dd></dl> <dl class="py class"> <dt class="sig sig-object py" id="collections.Sequence"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">Sequence</span></span><a class="headerlink" href="#collections.Sequence" title="Permalink to this definition">¶</a></dt> <dt class="sig sig-object py" id="collections.MutableSequence"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">MutableSequence</span></span><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"><span class="xref std std-term">sequences</span></a>.</p> </dd></dl> <dl class="py class"> <dt class="sig sig-object py" id="collections.Set"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">Set</span></span><a class="headerlink" href="#collections.Set" title="Permalink to this definition">¶</a></dt> <dt class="sig sig-object py" id="collections.MutableSet"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">MutableSet</span></span><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="py class"> <dt class="sig sig-object py" id="collections.Mapping"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">Mapping</span></span><a class="headerlink" href="#collections.Mapping" title="Permalink to this definition">¶</a></dt> <dt class="sig sig-object py" id="collections.MutableMapping"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">MutableMapping</span></span><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"><span class="xref std std-term">mappings</span></a>.</p> </dd></dl> <dl class="py class"> <dt class="sig sig-object py" id="collections.MappingView"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">MappingView</span></span><a class="headerlink" href="#collections.MappingView" title="Permalink to this definition">¶</a></dt> <dt class="sig sig-object py" id="collections.ItemsView"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">ItemsView</span></span><a class="headerlink" href="#collections.ItemsView" title="Permalink to this definition">¶</a></dt> <dt class="sig sig-object py" id="collections.KeysView"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">KeysView</span></span><a class="headerlink" href="#collections.KeysView" title="Permalink to this definition">¶</a></dt> <dt class="sig sig-object py" id="collections.ValuesView"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">ValuesView</span></span><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-dictionary-view"><span class="xref std std-term">views</span></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-default notranslate"><div class="highlight"><pre><span></span><span class="n">size</span> <span class="o">=</span> <span class="kc">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"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> API, it only necessary to supply the three underlying abstract methods: <code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code>. The ABC supplies the remaining methods such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">__and__()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">isdisjoint()</span></code></p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><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">''' Alternate set implementation favoring space over speed</span> <span class="sd"> and not requiring the set elements to be hashable. '''</span> <span class="k">def</span> <span class="fm">__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="fm">__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="fm">__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="fm">__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="s1">'abcdef'</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="s1">'defghi'</span><span class="p">)</span> <span class="n">overlap</span> <span class="o">=</span> <span class="n">s1</span> <span class="o">&</span> <span class="n">s2</span> <span class="c1"># The __and__() method is supported automatically</span> </pre></div> </div> <p>Notes on using <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> and <a class="reference internal" href="#collections.MutableSet" title="collections.MutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableSet</span></code></a> as a mixin:</p> <ol class="arabic simple"> <li><p>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 <code class="docutils literal notranslate"><span class="pre">ClassName(iterable)</span></code>. That assumption is factored-out to an internal classmethod called <code class="xref py py-meth docutils literal notranslate"><span class="pre">_from_iterable()</span></code> which calls <code class="docutils literal notranslate"><span class="pre">cls(iterable)</span></code> to produce a new set. If the <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> mixin is being used in a class with a different constructor signature, you will need to override <code class="xref py py-meth docutils literal notranslate"><span class="pre">_from_iterable()</span></code> with a classmethod that can construct new instances from an iterable argument.</p></li> <li><p>To override the comparisons (presumably for speed, as the semantics are fixed), redefine <code class="xref py py-meth docutils literal notranslate"><span class="pre">__le__()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">__ge__()</span></code>, then the other operations will automatically follow suit.</p></li> <li><p>The <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> mixin provides a <code class="xref py py-meth docutils literal notranslate"><span class="pre">_hash()</span></code> method to compute a hash value for the set; however, <code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code> is not defined because not all sets are hashable or immutable. To add set hashability using mixins, inherit from both <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Set()</span></code></a> and <a class="reference internal" href="#collections.Hashable" title="collections.Hashable"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Hashable()</span></code></a>, then define <code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">Set._hash</span></code>.</p></li> </ol> <div class="admonition seealso"> <p class="admonition-title">See also</p> <ul class="simple"> <li><p><a class="reference external" href="https://code.activestate.com/recipes/576694/">OrderedSet recipe</a> for an example built on <a class="reference internal" href="#collections.MutableSet" title="collections.MutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableSet</span></code></a>.</p></li> <li><p>For more about ABCs, see the <a class="reference internal" href="abc.html#module-abc" title="abc: Abstract base classes according to PEP 3119."><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code></a> module and <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3119"><strong>PEP 3119</strong></a>.</p></li> </ul> </div> </section> </section> <div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h3><a href="../contents.html">Table of Contents</a></h3> <ul> <li><a class="reference internal" href="#">8.3. <code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code> — High-performance container datatypes</a><ul> <li><a class="reference internal" href="#counter-objects">8.3.1. <code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code> objects</a></li> <li><a class="reference internal" href="#deque-objects">8.3.2. <code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code> objects</a><ul> <li><a class="reference internal" href="#deque-recipes">8.3.2.1. <code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code> Recipes</a></li> </ul> </li> <li><a class="reference internal" href="#defaultdict-objects">8.3.3. <code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code> objects</a><ul> <li><a class="reference internal" href="#defaultdict-examples">8.3.3.1. <code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code> Examples</a></li> </ul> </li> <li><a class="reference internal" href="#namedtuple-factory-function-for-tuples-with-named-fields">8.3.4. <code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code> Factory Function for Tuples with Named Fields</a></li> <li><a class="reference internal" href="#ordereddict-objects">8.3.5. <code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code> objects</a><ul> <li><a class="reference internal" href="#ordereddict-examples-and-recipes">8.3.5.1. <code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code> 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"><span class="section-number">8.2. </span><code class="xref py py-mod docutils literal notranslate"><span class="pre">calendar</span></code> — General calendar-related functions</a></p> <h4>Next topic</h4> <p class="topless"><a href="heapq.html" title="next chapter"><span class="section-number">8.4. </span><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code> — Heap queue algorithm</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/library/collections.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3 id="searchlabel">Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/> <input type="submit" value="Go" /> </form> </div> </div> <script>$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <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="https://www.python.org/">Python</a> »</li> <li> <a href="../index.html">Python 2.7.18 documentation</a> » </li> <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="datatypes.html" ><span class="section-number">8. </span>Data Types</a> »</li> <li class="nav-item nav-item-this"><a href=""><span class="section-number">8.3. </span><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code> — High-performance container datatypes</a></li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 1990-2024, Python Software Foundation. <br /> The Python Software Foundation is a non-profit corporation. <a href="https://www.python.org/psf/donations/">Please donate.</a> <br /> Last updated on November 21, 2024. <a href="../bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 4.3.2. </div> </body> </html>