Sophie

Sophie

distrib > Mageia > 3 > i586 > media > core-updates > by-pkgid > 50402eac2a16508b365658612a898528 > files > 814

python3-docs-3.3.0-4.3.mga3.noarch.rpm



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>4. Built-in Types &mdash; Python v3.3.0 documentation</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.3.0',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v3.3.0 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v3.3.0 documentation" href="../index.html" />
    <link rel="up" title="The Python Standard Library" href="index.html" />
    <link rel="next" title="5. Built-in Exceptions" href="exceptions.html" />
    <link rel="prev" title="3. Built-in Constants" href="constants.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
 

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="exceptions.html" title="5. Built-in Exceptions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="constants.html" title="3. Built-in Constants"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="http://www.python.org/">Python</a> &raquo;</li>
        <li><a href="../index.html">3.3.0 Documentation</a> &raquo;</li>

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

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="built-in-types">
<span id="bltin-types"></span><h1>4. Built-in Types<a class="headerlink" href="#built-in-types" title="Permalink to this headline">¶</a></h1>
<p>The following sections describe the standard types that are built into the
interpreter.</p>
<p id="index-0">The principal built-in types are numerics, sequences, mappings, classes,
instances and exceptions.</p>
<p>Some collection classes are mutable.  The methods that add, subtract, or
rearrange their members in place, and don&#8217;t return a specific item, never return
the collection instance itself but <tt class="xref docutils literal"><span class="pre">None</span></tt>.</p>
<p>Some operations are supported by several object types; in particular,
practically all objects can be compared, tested for truth value, and converted
to a string (with the <a class="reference internal" href="functions.html#repr" title="repr"><tt class="xref py py-func docutils literal"><span class="pre">repr()</span></tt></a> function or the slightly different
<a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-func docutils literal"><span class="pre">str()</span></tt></a> function).  The latter function is implicitly used when an object is
written by the <a class="reference internal" href="functions.html#print" title="print"><tt class="xref py py-func docutils literal"><span class="pre">print()</span></tt></a> function.</p>
<div class="section" id="truth-value-testing">
<span id="truth"></span><h2>4.1. Truth Value Testing<a class="headerlink" href="#truth-value-testing" title="Permalink to this headline">¶</a></h2>
<p id="index-1">Any object can be tested for truth value, for use in an <a class="reference internal" href="../reference/compound_stmts.html#if"><tt class="xref std std-keyword docutils literal"><span class="pre">if</span></tt></a> or
<a class="reference internal" href="../reference/compound_stmts.html#while"><tt class="xref std std-keyword docutils literal"><span class="pre">while</span></tt></a> condition or as operand of the Boolean operations below. The
following values are considered false:</p>
<blockquote>
<div></div></blockquote>
<ul id="index-2">
<li><p class="first"><tt class="xref docutils literal"><span class="pre">None</span></tt></p>
</li>
<li id="index-3"><p class="first"><tt class="xref docutils literal"><span class="pre">False</span></tt></p>
</li>
<li><p class="first">zero of any numeric type, for example, <tt class="docutils literal"><span class="pre">0</span></tt>, <tt class="docutils literal"><span class="pre">0.0</span></tt>, <tt class="docutils literal"><span class="pre">0j</span></tt>.</p>
</li>
<li><p class="first">any empty sequence, for example, <tt class="docutils literal"><span class="pre">''</span></tt>, <tt class="docutils literal"><span class="pre">()</span></tt>, <tt class="docutils literal"><span class="pre">[]</span></tt>.</p>
</li>
<li><p class="first">any empty mapping, for example, <tt class="docutils literal"><span class="pre">{}</span></tt>.</p>
</li>
<li><p class="first">instances of user-defined classes, if the class defines a <a class="reference internal" href="../reference/datamodel.html#object.__bool__" title="object.__bool__"><tt class="xref py py-meth docutils literal"><span class="pre">__bool__()</span></tt></a> or
<a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><tt class="xref py py-meth docutils literal"><span class="pre">__len__()</span></tt></a> method, when that method returns the integer zero or
<a class="reference internal" href="functions.html#bool" title="bool"><tt class="xref py py-class docutils literal"><span class="pre">bool</span></tt></a> value <tt class="xref docutils literal"><span class="pre">False</span></tt>. <a class="footnote-reference" href="#id10" id="id1">[1]</a></p>
</li>
</ul>
<p id="index-4">All other values are considered true &#8212; so objects of many types are always
true.</p>
<p id="index-5">Operations and built-in functions that have a Boolean result always return <tt class="docutils literal"><span class="pre">0</span></tt>
or <tt class="xref docutils literal"><span class="pre">False</span></tt> for false and <tt class="docutils literal"><span class="pre">1</span></tt> or <tt class="xref docutils literal"><span class="pre">True</span></tt> for true, unless otherwise stated.
(Important exception: the Boolean operations <tt class="docutils literal"><span class="pre">or</span></tt> and <tt class="docutils literal"><span class="pre">and</span></tt> always return
one of their operands.)</p>
</div>
<div class="section" id="boolean-operations-and-or-not">
<span id="boolean"></span><h2>4.2. Boolean Operations &#8212; <a class="reference internal" href="../reference/expressions.html#and"><tt class="xref std std-keyword docutils literal"><span class="pre">and</span></tt></a>, <a class="reference internal" href="../reference/expressions.html#or"><tt class="xref std std-keyword docutils literal"><span class="pre">or</span></tt></a>, <a class="reference internal" href="../reference/expressions.html#not"><tt class="xref std std-keyword docutils literal"><span class="pre">not</span></tt></a><a class="headerlink" href="#boolean-operations-and-or-not" title="Permalink to this headline">¶</a></h2>
<p id="index-6">These are the Boolean operations, ordered by ascending priority:</p>
<table border="1" class="docutils">
<colgroup>
<col width="25%" />
<col width="62%" />
<col width="13%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Operation</th>
<th class="head">Result</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">or</span> <span class="pre">y</span></tt></td>
<td>if <em>x</em> is false, then <em>y</em>, else
<em>x</em></td>
<td>(1)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">and</span> <span class="pre">y</span></tt></td>
<td>if <em>x</em> is false, then <em>x</em>, else
<em>y</em></td>
<td>(2)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">not</span> <span class="pre">x</span></tt></td>
<td>if <em>x</em> is false, then <tt class="xref docutils literal"><span class="pre">True</span></tt>,
else <tt class="xref docutils literal"><span class="pre">False</span></tt></td>
<td>(3)</td>
</tr>
</tbody>
</table>
<p id="index-7">Notes:</p>
<ol class="arabic simple">
<li>This is a short-circuit operator, so it only evaluates the second
argument if the first one is <a class="reference internal" href="constants.html#False" title="False"><tt class="xref py py-const xref docutils literal"><span class="pre">False</span></tt></a>.</li>
<li>This is a short-circuit operator, so it only evaluates the second
argument if the first one is <a class="reference internal" href="constants.html#True" title="True"><tt class="xref py py-const xref docutils literal"><span class="pre">True</span></tt></a>.</li>
<li><tt class="docutils literal"><span class="pre">not</span></tt> has a lower priority than non-Boolean operators, so <tt class="docutils literal"><span class="pre">not</span> <span class="pre">a</span> <span class="pre">==</span> <span class="pre">b</span></tt> is
interpreted as <tt class="docutils literal"><span class="pre">not</span> <span class="pre">(a</span> <span class="pre">==</span> <span class="pre">b)</span></tt>, and <tt class="docutils literal"><span class="pre">a</span> <span class="pre">==</span> <span class="pre">not</span> <span class="pre">b</span></tt> is a syntax error.</li>
</ol>
</div>
<div class="section" id="comparisons">
<span id="stdcomparisons"></span><h2>4.3. Comparisons<a class="headerlink" href="#comparisons" title="Permalink to this headline">¶</a></h2>
<p id="index-8">There are eight comparison operations in Python.  They all have the same
priority (which is higher than that of the Boolean operations).  Comparisons can
be chained arbitrarily; for example, <tt class="docutils literal"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span> <span class="pre">&lt;=</span> <span class="pre">z</span></tt> is equivalent to <tt class="docutils literal"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span> <span class="pre">and</span>
<span class="pre">y</span> <span class="pre">&lt;=</span> <span class="pre">z</span></tt>, except that <em>y</em> is evaluated only once (but in both cases <em>z</em> is not
evaluated at all when <tt class="docutils literal"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span></tt> is found to be false).</p>
<p>This table summarizes the comparison operations:</p>
<table border="1" class="docutils">
<colgroup>
<col width="32%" />
<col width="68%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Operation</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><tt class="docutils literal"><span class="pre">&lt;</span></tt></td>
<td>strictly less than</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">&lt;=</span></tt></td>
<td>less than or equal</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">&gt;</span></tt></td>
<td>strictly greater than</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">&gt;=</span></tt></td>
<td>greater than or equal</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">==</span></tt></td>
<td>equal</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">!=</span></tt></td>
<td>not equal</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">is</span></tt></td>
<td>object identity</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">is</span> <span class="pre">not</span></tt></td>
<td>negated object identity</td>
</tr>
</tbody>
</table>
<p id="index-9">Objects of different types, except different numeric types, never compare equal.
Furthermore, some types (for example, function objects) support only a degenerate
notion of comparison where any two objects of that type are unequal.  The <tt class="docutils literal"><span class="pre">&lt;</span></tt>,
<tt class="docutils literal"><span class="pre">&lt;=</span></tt>, <tt class="docutils literal"><span class="pre">&gt;</span></tt> and <tt class="docutils literal"><span class="pre">&gt;=</span></tt> operators will raise a <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> exception when
comparing a complex number with another built-in numeric type, when the objects
are of different types that cannot be compared, or in other cases where there is
no defined ordering.</p>
<p id="index-10">Non-identical instances of a class normally compare as non-equal unless the
class defines the <a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> method.</p>
<p>Instances of a class cannot be ordered with respect to other instances of the
same class, or other types of object, unless the class defines enough of the
methods <a class="reference internal" href="../reference/datamodel.html#object.__lt__" title="object.__lt__"><tt class="xref py py-meth docutils literal"><span class="pre">__lt__()</span></tt></a>, <a class="reference internal" href="../reference/datamodel.html#object.__le__" title="object.__le__"><tt class="xref py py-meth docutils literal"><span class="pre">__le__()</span></tt></a>, <a class="reference internal" href="../reference/datamodel.html#object.__gt__" title="object.__gt__"><tt class="xref py py-meth docutils literal"><span class="pre">__gt__()</span></tt></a>, and <a class="reference internal" href="../reference/datamodel.html#object.__ge__" title="object.__ge__"><tt class="xref py py-meth docutils literal"><span class="pre">__ge__()</span></tt></a> (in
general, <a class="reference internal" href="../reference/datamodel.html#object.__lt__" title="object.__lt__"><tt class="xref py py-meth docutils literal"><span class="pre">__lt__()</span></tt></a> and <a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> are sufficient, if you want the
conventional meanings of the comparison operators).</p>
<p>The behavior of the <a class="reference internal" href="../reference/expressions.html#is"><tt class="xref std std-keyword docutils literal"><span class="pre">is</span></tt></a> and <a class="reference internal" href="../reference/expressions.html#is-not"><tt class="xref std std-keyword docutils literal"><span class="pre">is</span> <span class="pre">not</span></tt></a> operators cannot be
customized; also they can be applied to any two objects and never raise an
exception.</p>
<p id="index-11">Two more operations with the same syntactic priority, <a class="reference internal" href="../reference/expressions.html#in"><tt class="xref std std-keyword docutils literal"><span class="pre">in</span></tt></a> and
<a class="reference internal" href="../reference/expressions.html#not-in"><tt class="xref std std-keyword docutils literal"><span class="pre">not</span> <span class="pre">in</span></tt></a>, are supported only by sequence types (below).</p>
</div>
<div class="section" id="numeric-types-int-float-complex">
<span id="typesnumeric"></span><h2>4.4. Numeric Types &#8212; <a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a>, <a class="reference internal" href="functions.html#float" title="float"><tt class="xref py py-class docutils literal"><span class="pre">float</span></tt></a>, <a class="reference internal" href="functions.html#complex" title="complex"><tt class="xref py py-class docutils literal"><span class="pre">complex</span></tt></a><a class="headerlink" href="#numeric-types-int-float-complex" title="Permalink to this headline">¶</a></h2>
<p id="index-12">There are three distinct numeric types: <em class="dfn">integers</em>, <em class="dfn">floating
point numbers</em>, and <em class="dfn">complex numbers</em>.  In addition, Booleans are a
subtype of integers.  Integers have unlimited precision.  Floating point
numbers are usually implemented using <tt class="xref c c-type docutils literal"><span class="pre">double</span></tt> in C; information
about the precision and internal representation of floating point
numbers for the machine on which your program is running is available
in <a class="reference internal" href="sys.html#sys.float_info" title="sys.float_info"><tt class="xref py py-data docutils literal"><span class="pre">sys.float_info</span></tt></a>.  Complex numbers have a real and imaginary
part, which are each a floating point number.  To extract these parts
from a complex number <em>z</em>, use <tt class="docutils literal"><span class="pre">z.real</span></tt> and <tt class="docutils literal"><span class="pre">z.imag</span></tt>. (The standard
library includes additional numeric types, <a class="reference internal" href="fractions.html#module-fractions" title="fractions: Rational numbers."><tt class="xref py py-mod docutils literal"><span class="pre">fractions</span></tt></a> that hold
rationals, and <a class="reference internal" href="decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><tt class="xref py py-mod docutils literal"><span class="pre">decimal</span></tt></a> that hold floating-point numbers with
user-definable precision.)</p>
<p id="index-13">Numbers are created by numeric literals or as the result of built-in functions
and operators.  Unadorned integer literals (including hex, octal and binary
numbers) yield integers.  Numeric literals containing a decimal point or an
exponent sign yield floating point numbers.  Appending <tt class="docutils literal"><span class="pre">'j'</span></tt> or <tt class="docutils literal"><span class="pre">'J'</span></tt> to a
numeric literal yields an imaginary number (a complex number with a zero real
part) which you can add to an integer or float to get a complex number with real
and imaginary parts.</p>
<p id="index-14">Python fully supports mixed arithmetic: when a binary arithmetic operator has
operands of different numeric types, the operand with the &#8220;narrower&#8221; type is
widened to that of the other, where integer is narrower than floating point,
which is narrower than complex.  Comparisons between numbers of mixed type use
the same rule. <a class="footnote-reference" href="#id11" id="id2">[2]</a> The constructors <a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-func docutils literal"><span class="pre">int()</span></tt></a>, <a class="reference internal" href="functions.html#float" title="float"><tt class="xref py py-func docutils literal"><span class="pre">float()</span></tt></a>, and
<a class="reference internal" href="functions.html#complex" title="complex"><tt class="xref py py-func docutils literal"><span class="pre">complex()</span></tt></a> can be used to produce numbers of a specific type.</p>
<p>All numeric types (except complex) support the following operations, sorted by
ascending priority (operations in the same box have the same priority; all
numeric operations have a higher priority than comparison operations):</p>
<table border="1" class="docutils">
<colgroup>
<col width="25%" />
<col width="40%" />
<col width="11%" />
<col width="24%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Operation</th>
<th class="head">Result</th>
<th class="head">Notes</th>
<th class="head">Full documentation</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></tt></td>
<td>sum of <em>x</em> and <em>y</em></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">-</span> <span class="pre">y</span></tt></td>
<td>difference of <em>x</em> and <em>y</em></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">*</span> <span class="pre">y</span></tt></td>
<td>product of <em>x</em> and <em>y</em></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">/</span> <span class="pre">y</span></tt></td>
<td>quotient of <em>x</em> and <em>y</em></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">//</span> <span class="pre">y</span></tt></td>
<td>floored quotient of <em>x</em> and
<em>y</em></td>
<td>(1)</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">%</span> <span class="pre">y</span></tt></td>
<td>remainder of <tt class="docutils literal"><span class="pre">x</span> <span class="pre">/</span> <span class="pre">y</span></tt></td>
<td>(2)</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">-x</span></tt></td>
<td><em>x</em> negated</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">+x</span></tt></td>
<td><em>x</em> unchanged</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">abs(x)</span></tt></td>
<td>absolute value or magnitude of
<em>x</em></td>
<td>&nbsp;</td>
<td><a class="reference internal" href="functions.html#abs" title="abs"><tt class="xref py py-func docutils literal"><span class="pre">abs()</span></tt></a></td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">int(x)</span></tt></td>
<td><em>x</em> converted to integer</td>
<td>(3)(6)</td>
<td><a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-func docutils literal"><span class="pre">int()</span></tt></a></td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">float(x)</span></tt></td>
<td><em>x</em> converted to floating point</td>
<td>(4)(6)</td>
<td><a class="reference internal" href="functions.html#float" title="float"><tt class="xref py py-func docutils literal"><span class="pre">float()</span></tt></a></td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">complex(re,</span> <span class="pre">im)</span></tt></td>
<td>a complex number with real part
<em>re</em>, imaginary part <em>im</em>.
<em>im</em> defaults to zero.</td>
<td>(6)</td>
<td><a class="reference internal" href="functions.html#complex" title="complex"><tt class="xref py py-func docutils literal"><span class="pre">complex()</span></tt></a></td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">c.conjugate()</span></tt></td>
<td>conjugate of the complex number
<em>c</em></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">divmod(x,</span> <span class="pre">y)</span></tt></td>
<td>the pair <tt class="docutils literal"><span class="pre">(x</span> <span class="pre">//</span> <span class="pre">y,</span> <span class="pre">x</span> <span class="pre">%</span> <span class="pre">y)</span></tt></td>
<td>(2)</td>
<td><a class="reference internal" href="functions.html#divmod" title="divmod"><tt class="xref py py-func docutils literal"><span class="pre">divmod()</span></tt></a></td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">pow(x,</span> <span class="pre">y)</span></tt></td>
<td><em>x</em> to the power <em>y</em></td>
<td>(5)</td>
<td><a class="reference internal" href="functions.html#pow" title="pow"><tt class="xref py py-func docutils literal"><span class="pre">pow()</span></tt></a></td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">**</span> <span class="pre">y</span></tt></td>
<td><em>x</em> to the power <em>y</em></td>
<td>(5)</td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
<p id="index-15">Notes:</p>
<ol class="arabic">
<li><p class="first">Also referred to as integer division.  The resultant value is a whole
integer, though the result&#8217;s type is not necessarily int.  The result is
always rounded towards minus infinity: <tt class="docutils literal"><span class="pre">1//2</span></tt> is <tt class="docutils literal"><span class="pre">0</span></tt>, <tt class="docutils literal"><span class="pre">(-1)//2</span></tt> is
<tt class="docutils literal"><span class="pre">-1</span></tt>, <tt class="docutils literal"><span class="pre">1//(-2)</span></tt> is <tt class="docutils literal"><span class="pre">-1</span></tt>, and <tt class="docutils literal"><span class="pre">(-1)//(-2)</span></tt> is <tt class="docutils literal"><span class="pre">0</span></tt>.</p>
</li>
<li><p class="first">Not for complex numbers.  Instead convert to floats using <a class="reference internal" href="functions.html#abs" title="abs"><tt class="xref py py-func docutils literal"><span class="pre">abs()</span></tt></a> if
appropriate.</p>
</li>
<li><p id="index-16">Conversion from floating point to integer may round or truncate
as in C; see functions <tt class="xref py py-func docutils literal"><span class="pre">floor()</span></tt> and <tt class="xref py py-func docutils literal"><span class="pre">ceil()</span></tt> in the <a class="reference internal" href="math.html#module-math" title="math: Mathematical functions (sin() etc.)."><tt class="xref py py-mod docutils literal"><span class="pre">math</span></tt></a> module
for well-defined conversions.</p>
</li>
<li><p class="first">float also accepts the strings &#8220;nan&#8221; and &#8220;inf&#8221; with an optional prefix &#8220;+&#8221;
or &#8220;-&#8221; for Not a Number (NaN) and positive or negative infinity.</p>
</li>
<li><p class="first">Python defines <tt class="docutils literal"><span class="pre">pow(0,</span> <span class="pre">0)</span></tt> and <tt class="docutils literal"><span class="pre">0</span> <span class="pre">**</span> <span class="pre">0</span></tt> to be <tt class="docutils literal"><span class="pre">1</span></tt>, as is common for
programming languages.</p>
</li>
<li><p class="first">The numeric literals accepted include the digits <tt class="docutils literal"><span class="pre">0</span></tt> to <tt class="docutils literal"><span class="pre">9</span></tt> or any
Unicode equivalent (code points with the <tt class="docutils literal"><span class="pre">Nd</span></tt> property).</p>
<p>See <a class="reference external" href="http://www.unicode.org/Public/6.0.0/ucd/extracted/DerivedNumericType.txt">http://www.unicode.org/Public/6.0.0/ucd/extracted/DerivedNumericType.txt</a>
for a complete list of code points with the <tt class="docutils literal"><span class="pre">Nd</span></tt> property.</p>
</li>
</ol>
<p>All <a class="reference internal" href="numbers.html#numbers.Real" title="numbers.Real"><tt class="xref py py-class docutils literal"><span class="pre">numbers.Real</span></tt></a> types (<a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a> and <a class="reference internal" href="functions.html#float" title="float"><tt class="xref py py-class docutils literal"><span class="pre">float</span></tt></a>) also include
the following operations:</p>
<table border="1" class="docutils">
<colgroup>
<col width="31%" />
<col width="56%" />
<col width="13%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Operation</th>
<th class="head">Result</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><tt class="docutils literal"><span class="pre">math.trunc(x)</span></tt></td>
<td><em>x</em> truncated to Integral</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">round(x[,</span> <span class="pre">n])</span></tt></td>
<td><em>x</em> rounded to n digits,
rounding half to even. If n is
omitted, it defaults to 0.</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">math.floor(x)</span></tt></td>
<td>the greatest integral float &lt;= <em>x</em></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">math.ceil(x)</span></tt></td>
<td>the least integral float &gt;= <em>x</em></td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
<p>For additional numeric operations see the <a class="reference internal" href="math.html#module-math" title="math: Mathematical functions (sin() etc.)."><tt class="xref py py-mod docutils literal"><span class="pre">math</span></tt></a> and <a class="reference internal" href="cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><tt class="xref py py-mod docutils literal"><span class="pre">cmath</span></tt></a>
modules.</p>
<div class="section" id="bitwise-operations-on-integer-types">
<span id="bitstring-ops"></span><h3>4.4.1. Bitwise Operations on Integer Types<a class="headerlink" href="#bitwise-operations-on-integer-types" title="Permalink to this headline">¶</a></h3>
<p id="index-17">Bitwise operations only make sense for integers.  Negative numbers are treated
as their 2&#8217;s complement value (this assumes a sufficiently large number of bits
that no overflow occurs during the operation).</p>
<p>The priorities of the binary bitwise operations are all lower than the numeric
operations and higher than the comparisons; the unary operation <tt class="docutils literal"><span class="pre">~</span></tt> has the
same priority as the other unary numeric operations (<tt class="docutils literal"><span class="pre">+</span></tt> and <tt class="docutils literal"><span class="pre">-</span></tt>).</p>
<p>This table lists the bitwise operations sorted in ascending priority
(operations in the same box have the same priority):</p>
<table border="1" class="docutils">
<colgroup>
<col width="22%" />
<col width="59%" />
<col width="19%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Operation</th>
<th class="head">Result</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">|</span> <span class="pre">y</span></tt></td>
<td>bitwise <em class="dfn">or</em> of <em>x</em> and
<em>y</em></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">^</span> <span class="pre">y</span></tt></td>
<td>bitwise <em class="dfn">exclusive or</em> of
<em>x</em> and <em>y</em></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">&amp;</span> <span class="pre">y</span></tt></td>
<td>bitwise <em class="dfn">and</em> of <em>x</em> and
<em>y</em></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">&lt;&lt;</span> <span class="pre">n</span></tt></td>
<td><em>x</em> shifted left by <em>n</em> bits</td>
<td>(1)(2)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">&gt;&gt;</span> <span class="pre">n</span></tt></td>
<td><em>x</em> shifted right by <em>n</em> bits</td>
<td>(1)(3)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">~x</span></tt></td>
<td>the bits of <em>x</em> inverted</td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic simple">
<li>Negative shift counts are illegal and cause a <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> to be raised.</li>
<li>A left shift by <em>n</em> bits is equivalent to multiplication by <tt class="docutils literal"><span class="pre">pow(2,</span> <span class="pre">n)</span></tt>
without overflow check.</li>
<li>A right shift by <em>n</em> bits is equivalent to division by <tt class="docutils literal"><span class="pre">pow(2,</span> <span class="pre">n)</span></tt> without
overflow check.</li>
</ol>
</div>
<div class="section" id="additional-methods-on-integer-types">
<h3>4.4.2. Additional Methods on Integer Types<a class="headerlink" href="#additional-methods-on-integer-types" title="Permalink to this headline">¶</a></h3>
<p>The int type implements the <a class="reference internal" href="numbers.html#numbers.Integral" title="numbers.Integral"><tt class="xref py py-class docutils literal"><span class="pre">numbers.Integral</span></tt></a> <a class="reference internal" href="../glossary.html#term-abstract-base-class"><em class="xref std std-term">abstract base
class</em></a>. In addition, it provides one more method:</p>
<dl class="method">
<dt id="int.bit_length">
<tt class="descclassname">int.</tt><tt class="descname">bit_length</tt><big>(</big><big>)</big><a class="headerlink" href="#int.bit_length" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of bits necessary to represent an integer in binary,
excluding the sign and leading zeros:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">=</span> <span class="o">-</span><span class="mi">37</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">bin</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="go">&#39;-0b100101&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">n</span><span class="o">.</span><span class="n">bit_length</span><span class="p">()</span>
<span class="go">6</span>
</pre></div>
</div>
<p>More precisely, if <tt class="docutils literal"><span class="pre">x</span></tt> is nonzero, then <tt class="docutils literal"><span class="pre">x.bit_length()</span></tt> is the
unique positive integer <tt class="docutils literal"><span class="pre">k</span></tt> such that <tt class="docutils literal"><span class="pre">2**(k-1)</span> <span class="pre">&lt;=</span> <span class="pre">abs(x)</span> <span class="pre">&lt;</span> <span class="pre">2**k</span></tt>.
Equivalently, when <tt class="docutils literal"><span class="pre">abs(x)</span></tt> is small enough to have a correctly
rounded logarithm, then <tt class="docutils literal"><span class="pre">k</span> <span class="pre">=</span> <span class="pre">1</span> <span class="pre">+</span> <span class="pre">int(log(abs(x),</span> <span class="pre">2))</span></tt>.
If <tt class="docutils literal"><span class="pre">x</span></tt> is zero, then <tt class="docutils literal"><span class="pre">x.bit_length()</span></tt> returns <tt class="docutils literal"><span class="pre">0</span></tt>.</p>
<p>Equivalent to:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">bit_length</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="n">s</span> <span class="o">=</span> <span class="nb">bin</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>       <span class="c"># binary representation:  bin(-37) --&gt; &#39;-0b100101&#39;</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">lstrip</span><span class="p">(</span><span class="s">&#39;-0b&#39;</span><span class="p">)</span> <span class="c"># remove leading zeros and minus sign</span>
    <span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>       <span class="c"># len(&#39;100101&#39;) --&gt; 6</span>
</pre></div>
</div>
<p class="versionadded">
<span class="versionmodified">New in version 3.1.</span> </p>
</dd></dl>

<dl class="method">
<dt id="int.to_bytes">
<tt class="descclassname">int.</tt><tt class="descname">to_bytes</tt><big>(</big><em>length</em>, <em>byteorder</em>, <em>*</em>, <em>signed=False</em><big>)</big><a class="headerlink" href="#int.to_bytes" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an array of bytes representing an integer.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span><span class="o">.</span><span class="n">to_bytes</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s">&#39;big&#39;</span><span class="p">)</span>
<span class="go">b&#39;\x04\x00&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span><span class="o">.</span><span class="n">to_bytes</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s">&#39;big&#39;</span><span class="p">)</span>
<span class="go">b&#39;\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="o">-</span><span class="mi">1024</span><span class="p">)</span><span class="o">.</span><span class="n">to_bytes</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s">&#39;big&#39;</span><span class="p">,</span> <span class="n">signed</span><span class="o">=</span><span class="k">True</span><span class="p">)</span>
<span class="go">b&#39;\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">1000</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">to_bytes</span><span class="p">((</span><span class="n">x</span><span class="o">.</span><span class="n">bit_length</span><span class="p">()</span> <span class="o">//</span> <span class="mi">8</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s">&#39;little&#39;</span><span class="p">)</span>
<span class="go">b&#39;\xe8\x03&#39;</span>
</pre></div>
</div>
<p>The integer is represented using <em>length</em> bytes.  An <a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><tt class="xref py py-exc docutils literal"><span class="pre">OverflowError</span></tt></a>
is raised if the integer is not representable with the given number of
bytes.</p>
<p>The <em>byteorder</em> argument determines the byte order used to represent the
integer.  If <em>byteorder</em> is <tt class="docutils literal"><span class="pre">&quot;big&quot;</span></tt>, the most significant byte is at the
beginning of the byte array.  If <em>byteorder</em> is <tt class="docutils literal"><span class="pre">&quot;little&quot;</span></tt>, the most
significant byte is at the end of the byte array.  To request the native
byte order of the host system, use <a class="reference internal" href="sys.html#sys.byteorder" title="sys.byteorder"><tt class="xref py py-data docutils literal"><span class="pre">sys.byteorder</span></tt></a> as the byte order
value.</p>
<p>The <em>signed</em> argument determines whether two&#8217;s complement is used to
represent the integer.  If <em>signed</em> is <tt class="xref docutils literal"><span class="pre">False</span></tt> and a negative integer is
given, an <a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><tt class="xref py py-exc docutils literal"><span class="pre">OverflowError</span></tt></a> is raised. The default value for <em>signed</em>
is <tt class="xref docutils literal"><span class="pre">False</span></tt>.</p>
<p class="versionadded">
<span class="versionmodified">New in version 3.2.</span> </p>
</dd></dl>

<dl class="classmethod">
<dt id="int.from_bytes">
<em class="property">classmethod </em><tt class="descclassname">int.</tt><tt class="descname">from_bytes</tt><big>(</big><em>bytes</em>, <em>byteorder</em>, <em>*</em>, <em>signed=False</em><big>)</big><a class="headerlink" href="#int.from_bytes" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the integer represented by the given array of bytes.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">from_bytes</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;</span><span class="se">\x00\x10</span><span class="s">&#39;</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s">&#39;big&#39;</span><span class="p">)</span>
<span class="go">16</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">from_bytes</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;</span><span class="se">\x00\x10</span><span class="s">&#39;</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s">&#39;little&#39;</span><span class="p">)</span>
<span class="go">4096</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">from_bytes</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;</span><span class="se">\xfc\x00</span><span class="s">&#39;</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s">&#39;big&#39;</span><span class="p">,</span> <span class="n">signed</span><span class="o">=</span><span class="k">True</span><span class="p">)</span>
<span class="go">-1024</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">from_bytes</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;</span><span class="se">\xfc\x00</span><span class="s">&#39;</span><span class="p">,</span> <span class="n">byteorder</span><span class="o">=</span><span class="s">&#39;big&#39;</span><span class="p">,</span> <span class="n">signed</span><span class="o">=</span><span class="k">False</span><span class="p">)</span>
<span class="go">64512</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">from_bytes</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="mi">0</span><span class="p">],</span> <span class="n">byteorder</span><span class="o">=</span><span class="s">&#39;big&#39;</span><span class="p">)</span>
<span class="go">16711680</span>
</pre></div>
</div>
<p>The argument <em>bytes</em> must either support the buffer protocol or be an
iterable producing bytes. <a class="reference internal" href="functions.html#bytes" title="bytes"><tt class="xref py py-class docutils literal"><span class="pre">bytes</span></tt></a> and <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a> are
examples of built-in objects that support the buffer protocol.</p>
<p>The <em>byteorder</em> argument determines the byte order used to represent the
integer.  If <em>byteorder</em> is <tt class="docutils literal"><span class="pre">&quot;big&quot;</span></tt>, the most significant byte is at the
beginning of the byte array.  If <em>byteorder</em> is <tt class="docutils literal"><span class="pre">&quot;little&quot;</span></tt>, the most
significant byte is at the end of the byte array.  To request the native
byte order of the host system, use <a class="reference internal" href="sys.html#sys.byteorder" title="sys.byteorder"><tt class="xref py py-data docutils literal"><span class="pre">sys.byteorder</span></tt></a> as the byte order
value.</p>
<p>The <em>signed</em> argument indicates whether two&#8217;s complement is used to
represent the integer.</p>
<p class="versionadded">
<span class="versionmodified">New in version 3.2.</span> </p>
</dd></dl>

</div>
<div class="section" id="additional-methods-on-float">
<h3>4.4.3. Additional Methods on Float<a class="headerlink" href="#additional-methods-on-float" title="Permalink to this headline">¶</a></h3>
<p>The float type implements the <a class="reference internal" href="numbers.html#numbers.Real" title="numbers.Real"><tt class="xref py py-class docutils literal"><span class="pre">numbers.Real</span></tt></a> <a class="reference internal" href="../glossary.html#term-abstract-base-class"><em class="xref std std-term">abstract base
class</em></a>. float also has the following additional methods.</p>
<dl class="method">
<dt id="float.as_integer_ratio">
<tt class="descclassname">float.</tt><tt class="descname">as_integer_ratio</tt><big>(</big><big>)</big><a class="headerlink" href="#float.as_integer_ratio" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a pair of integers whose ratio is exactly equal to the
original float and with a positive denominator.  Raises
<a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><tt class="xref py py-exc docutils literal"><span class="pre">OverflowError</span></tt></a> on infinities and a <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> on
NaNs.</p>
</dd></dl>

<dl class="method">
<dt id="float.is_integer">
<tt class="descclassname">float.</tt><tt class="descname">is_integer</tt><big>(</big><big>)</big><a class="headerlink" href="#float.is_integer" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <tt class="xref docutils literal"><span class="pre">True</span></tt> if the float instance is finite with integral
value, and <tt class="xref docutils literal"><span class="pre">False</span></tt> otherwise:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="o">-</span><span class="mf">2.0</span><span class="p">)</span><span class="o">.</span><span class="n">is_integer</span><span class="p">()</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mf">3.2</span><span class="p">)</span><span class="o">.</span><span class="n">is_integer</span><span class="p">()</span>
<span class="go">False</span>
</pre></div>
</div>
</dd></dl>

<p>Two methods support conversion to
and from hexadecimal strings.  Since Python&#8217;s floats are stored
internally as binary numbers, converting a float to or from a
<em>decimal</em> string usually involves a small rounding error.  In
contrast, hexadecimal strings allow exact representation and
specification of floating-point numbers.  This can be useful when
debugging, and in numerical work.</p>
<dl class="method">
<dt id="float.hex">
<tt class="descclassname">float.</tt><tt class="descname">hex</tt><big>(</big><big>)</big><a class="headerlink" href="#float.hex" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a representation of a floating-point number as a hexadecimal
string.  For finite floating-point numbers, this representation
will always include a leading <tt class="docutils literal"><span class="pre">0x</span></tt> and a trailing <tt class="docutils literal"><span class="pre">p</span></tt> and
exponent.</p>
</dd></dl>

<dl class="classmethod">
<dt id="float.fromhex">
<em class="property">classmethod </em><tt class="descclassname">float.</tt><tt class="descname">fromhex</tt><big>(</big><em>s</em><big>)</big><a class="headerlink" href="#float.fromhex" title="Permalink to this definition">¶</a></dt>
<dd><p>Class method to return the float represented by a hexadecimal
string <em>s</em>.  The string <em>s</em> may have leading and trailing
whitespace.</p>
</dd></dl>

<p>Note that <a class="reference internal" href="#float.hex" title="float.hex"><tt class="xref py py-meth docutils literal"><span class="pre">float.hex()</span></tt></a> is an instance method, while
<a class="reference internal" href="#float.fromhex" title="float.fromhex"><tt class="xref py py-meth docutils literal"><span class="pre">float.fromhex()</span></tt></a> is a class method.</p>
<p>A hexadecimal string takes the form:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="p">[</span><span class="n">sign</span><span class="p">]</span> <span class="p">[</span><span class="s">&#39;0x&#39;</span><span class="p">]</span> <span class="n">integer</span> <span class="p">[</span><span class="s">&#39;.&#39;</span> <span class="n">fraction</span><span class="p">]</span> <span class="p">[</span><span class="s">&#39;p&#39;</span> <span class="n">exponent</span><span class="p">]</span>
</pre></div>
</div>
<p>where the optional <tt class="docutils literal"><span class="pre">sign</span></tt> may by either <tt class="docutils literal"><span class="pre">+</span></tt> or <tt class="docutils literal"><span class="pre">-</span></tt>, <tt class="docutils literal"><span class="pre">integer</span></tt>
and <tt class="docutils literal"><span class="pre">fraction</span></tt> are strings of hexadecimal digits, and <tt class="docutils literal"><span class="pre">exponent</span></tt>
is a decimal integer with an optional leading sign.  Case is not
significant, and there must be at least one hexadecimal digit in
either the integer or the fraction.  This syntax is similar to the
syntax specified in section 6.4.4.2 of the C99 standard, and also to
the syntax used in Java 1.5 onwards.  In particular, the output of
<a class="reference internal" href="#float.hex" title="float.hex"><tt class="xref py py-meth docutils literal"><span class="pre">float.hex()</span></tt></a> is usable as a hexadecimal floating-point literal in
C or Java code, and hexadecimal strings produced by C&#8217;s <tt class="docutils literal"><span class="pre">%a</span></tt> format
character or Java&#8217;s <tt class="docutils literal"><span class="pre">Double.toHexString</span></tt> are accepted by
<a class="reference internal" href="#float.fromhex" title="float.fromhex"><tt class="xref py py-meth docutils literal"><span class="pre">float.fromhex()</span></tt></a>.</p>
<p>Note that the exponent is written in decimal rather than hexadecimal,
and that it gives the power of 2 by which to multiply the coefficient.
For example, the hexadecimal string <tt class="docutils literal"><span class="pre">0x3.a7p10</span></tt> represents the
floating-point number <tt class="docutils literal"><span class="pre">(3</span> <span class="pre">+</span> <span class="pre">10./16</span> <span class="pre">+</span> <span class="pre">7./16**2)</span> <span class="pre">*</span> <span class="pre">2.0**10</span></tt>, or
<tt class="docutils literal"><span class="pre">3740.0</span></tt>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="o">.</span><span class="n">fromhex</span><span class="p">(</span><span class="s">&#39;0x3.a7p10&#39;</span><span class="p">)</span>
<span class="go">3740.0</span>
</pre></div>
</div>
<p>Applying the reverse conversion to <tt class="docutils literal"><span class="pre">3740.0</span></tt> gives a different
hexadecimal string representing the same number:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="o">.</span><span class="n">hex</span><span class="p">(</span><span class="mf">3740.0</span><span class="p">)</span>
<span class="go">&#39;0x1.d380000000000p+11&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="hashing-of-numeric-types">
<span id="numeric-hash"></span><h3>4.4.4. Hashing of numeric types<a class="headerlink" href="#hashing-of-numeric-types" title="Permalink to this headline">¶</a></h3>
<p>For numbers <tt class="docutils literal"><span class="pre">x</span></tt> and <tt class="docutils literal"><span class="pre">y</span></tt>, possibly of different types, it&#8217;s a requirement
that <tt class="docutils literal"><span class="pre">hash(x)</span> <span class="pre">==</span> <span class="pre">hash(y)</span></tt> whenever <tt class="docutils literal"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></tt> (see the <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a>
method documentation for more details).  For ease of implementation and
efficiency across a variety of numeric types (including <a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a>,
<a class="reference internal" href="functions.html#float" title="float"><tt class="xref py py-class docutils literal"><span class="pre">float</span></tt></a>, <a class="reference internal" href="decimal.html#decimal.Decimal" title="decimal.Decimal"><tt class="xref py py-class docutils literal"><span class="pre">decimal.Decimal</span></tt></a> and <a class="reference internal" href="fractions.html#fractions.Fraction" title="fractions.Fraction"><tt class="xref py py-class docutils literal"><span class="pre">fractions.Fraction</span></tt></a>)
Python&#8217;s hash for numeric types is based on a single mathematical function
that&#8217;s defined for any rational number, and hence applies to all instances of
<a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a> and <tt class="xref py py-class docutils literal"><span class="pre">fraction.Fraction</span></tt>, and all finite instances of
<a class="reference internal" href="functions.html#float" title="float"><tt class="xref py py-class docutils literal"><span class="pre">float</span></tt></a> and <a class="reference internal" href="decimal.html#decimal.Decimal" title="decimal.Decimal"><tt class="xref py py-class docutils literal"><span class="pre">decimal.Decimal</span></tt></a>.  Essentially, this function is
given by reduction modulo <tt class="docutils literal"><span class="pre">P</span></tt> for a fixed prime <tt class="docutils literal"><span class="pre">P</span></tt>.  The value of <tt class="docutils literal"><span class="pre">P</span></tt> is
made available to Python as the <tt class="xref py py-attr docutils literal"><span class="pre">modulus</span></tt> attribute of
<a class="reference internal" href="sys.html#sys.hash_info" title="sys.hash_info"><tt class="xref py py-data docutils literal"><span class="pre">sys.hash_info</span></tt></a>.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> Currently, the prime used is <tt class="docutils literal"><span class="pre">P</span> <span class="pre">=</span> <span class="pre">2**31</span> <span class="pre">-</span> <span class="pre">1</span></tt> on machines with 32-bit C
longs and <tt class="docutils literal"><span class="pre">P</span> <span class="pre">=</span> <span class="pre">2**61</span> <span class="pre">-</span> <span class="pre">1</span></tt> on machines with 64-bit C longs.</p>
</div>
<p>Here are the rules in detail:</p>
<ul class="simple">
<li>If <tt class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">m</span> <span class="pre">/</span> <span class="pre">n</span></tt> is a nonnegative rational number and <tt class="docutils literal"><span class="pre">n</span></tt> is not divisible
by <tt class="docutils literal"><span class="pre">P</span></tt>, define <tt class="docutils literal"><span class="pre">hash(x)</span></tt> as <tt class="docutils literal"><span class="pre">m</span> <span class="pre">*</span> <span class="pre">invmod(n,</span> <span class="pre">P)</span> <span class="pre">%</span> <span class="pre">P</span></tt>, where <tt class="docutils literal"><span class="pre">invmod(n,</span>
<span class="pre">P)</span></tt> gives the inverse of <tt class="docutils literal"><span class="pre">n</span></tt> modulo <tt class="docutils literal"><span class="pre">P</span></tt>.</li>
<li>If <tt class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">m</span> <span class="pre">/</span> <span class="pre">n</span></tt> is a nonnegative rational number and <tt class="docutils literal"><span class="pre">n</span></tt> is
divisible by <tt class="docutils literal"><span class="pre">P</span></tt> (but <tt class="docutils literal"><span class="pre">m</span></tt> is not) then <tt class="docutils literal"><span class="pre">n</span></tt> has no inverse
modulo <tt class="docutils literal"><span class="pre">P</span></tt> and the rule above doesn&#8217;t apply; in this case define
<tt class="docutils literal"><span class="pre">hash(x)</span></tt> to be the constant value <tt class="docutils literal"><span class="pre">sys.hash_info.inf</span></tt>.</li>
<li>If <tt class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">m</span> <span class="pre">/</span> <span class="pre">n</span></tt> is a negative rational number define <tt class="docutils literal"><span class="pre">hash(x)</span></tt>
as <tt class="docutils literal"><span class="pre">-hash(-x)</span></tt>.  If the resulting hash is <tt class="docutils literal"><span class="pre">-1</span></tt>, replace it with
<tt class="docutils literal"><span class="pre">-2</span></tt>.</li>
<li>The particular values <tt class="docutils literal"><span class="pre">sys.hash_info.inf</span></tt>, <tt class="docutils literal"><span class="pre">-sys.hash_info.inf</span></tt>
and <tt class="docutils literal"><span class="pre">sys.hash_info.nan</span></tt> are used as hash values for positive
infinity, negative infinity, or nans (respectively).  (All hashable
nans have the same hash value.)</li>
<li>For a <a class="reference internal" href="functions.html#complex" title="complex"><tt class="xref py py-class docutils literal"><span class="pre">complex</span></tt></a> number <tt class="docutils literal"><span class="pre">z</span></tt>, the hash values of the real
and imaginary parts are combined by computing <tt class="docutils literal"><span class="pre">hash(z.real)</span> <span class="pre">+</span>
<span class="pre">sys.hash_info.imag</span> <span class="pre">*</span> <span class="pre">hash(z.imag)</span></tt>, reduced modulo
<tt class="docutils literal"><span class="pre">2**sys.hash_info.width</span></tt> so that it lies in
<tt class="docutils literal"><span class="pre">range(-2**(sys.hash_info.width</span> <span class="pre">-</span> <span class="pre">1),</span> <span class="pre">2**(sys.hash_info.width</span> <span class="pre">-</span>
<span class="pre">1))</span></tt>.  Again, if the result is <tt class="docutils literal"><span class="pre">-1</span></tt>, it&#8217;s replaced with <tt class="docutils literal"><span class="pre">-2</span></tt>.</li>
</ul>
<p>To clarify the above rules, here&#8217;s some example Python code,
equivalent to the built-in hash, for computing the hash of a rational
number, <a class="reference internal" href="functions.html#float" title="float"><tt class="xref py py-class docutils literal"><span class="pre">float</span></tt></a>, or <a class="reference internal" href="functions.html#complex" title="complex"><tt class="xref py py-class docutils literal"><span class="pre">complex</span></tt></a>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">math</span>

<span class="k">def</span> <span class="nf">hash_fraction</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Compute the hash of a rational number m / n.</span>

<span class="sd">    Assumes m and n are integers, with n positive.</span>
<span class="sd">    Equivalent to hash(fractions.Fraction(m, n)).</span>

<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">P</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">hash_info</span><span class="o">.</span><span class="n">modulus</span>
    <span class="c"># Remove common factors of P.  (Unnecessary if m and n already coprime.)</span>
    <span class="k">while</span> <span class="n">m</span> <span class="o">%</span> <span class="n">P</span> <span class="o">==</span> <span class="n">n</span> <span class="o">%</span> <span class="n">P</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">m</span><span class="p">,</span> <span class="n">n</span> <span class="o">=</span> <span class="n">m</span> <span class="o">//</span> <span class="n">P</span><span class="p">,</span> <span class="n">n</span> <span class="o">//</span> <span class="n">P</span>

    <span class="k">if</span> <span class="n">n</span> <span class="o">%</span> <span class="n">P</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">hash_</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">hash_info</span><span class="o">.</span><span class="n">inf</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="c"># Fermat&#39;s Little Theorem: pow(n, P-1, P) is 1, so</span>
        <span class="c"># pow(n, P-2, P) gives the inverse of n modulo P.</span>
        <span class="n">hash_</span> <span class="o">=</span> <span class="p">(</span><span class="nb">abs</span><span class="p">(</span><span class="n">m</span><span class="p">)</span> <span class="o">%</span> <span class="n">P</span><span class="p">)</span> <span class="o">*</span> <span class="nb">pow</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="n">P</span> <span class="o">-</span> <span class="mi">2</span><span class="p">,</span> <span class="n">P</span><span class="p">)</span> <span class="o">%</span> <span class="n">P</span>
    <span class="k">if</span> <span class="n">m</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">hash_</span> <span class="o">=</span> <span class="o">-</span><span class="n">hash_</span>
    <span class="k">if</span> <span class="n">hash_</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="p">:</span>
        <span class="n">hash_</span> <span class="o">=</span> <span class="o">-</span><span class="mi">2</span>
    <span class="k">return</span> <span class="n">hash_</span>

<span class="k">def</span> <span class="nf">hash_float</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Compute the hash of a float x.&quot;&quot;&quot;</span>

    <span class="k">if</span> <span class="n">math</span><span class="o">.</span><span class="n">isnan</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">sys</span><span class="o">.</span><span class="n">hash_info</span><span class="o">.</span><span class="n">nan</span>
    <span class="k">elif</span> <span class="n">math</span><span class="o">.</span><span class="n">isinf</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">sys</span><span class="o">.</span><span class="n">hash_info</span><span class="o">.</span><span class="n">inf</span> <span class="k">if</span> <span class="n">x</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="k">else</span> <span class="o">-</span><span class="n">sys</span><span class="o">.</span><span class="n">hash_info</span><span class="o">.</span><span class="n">inf</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">hash_fraction</span><span class="p">(</span><span class="o">*</span><span class="n">x</span><span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">())</span>

<span class="k">def</span> <span class="nf">hash_complex</span><span class="p">(</span><span class="n">z</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Compute the hash of a complex number z.&quot;&quot;&quot;</span>

    <span class="n">hash_</span> <span class="o">=</span> <span class="n">hash_float</span><span class="p">(</span><span class="n">z</span><span class="o">.</span><span class="n">real</span><span class="p">)</span> <span class="o">+</span> <span class="n">sys</span><span class="o">.</span><span class="n">hash_info</span><span class="o">.</span><span class="n">imag</span> <span class="o">*</span> <span class="n">hash_float</span><span class="p">(</span><span class="n">z</span><span class="o">.</span><span class="n">imag</span><span class="p">)</span>
    <span class="c"># do a signed reduction modulo 2**sys.hash_info.width</span>
    <span class="n">M</span> <span class="o">=</span> <span class="mi">2</span><span class="o">**</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">hash_info</span><span class="o">.</span><span class="n">width</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span>
    <span class="n">hash_</span> <span class="o">=</span> <span class="p">(</span><span class="n">hash_</span> <span class="o">&amp;</span> <span class="p">(</span><span class="n">M</span> <span class="o">-</span> <span class="mi">1</span><span class="p">))</span> <span class="o">-</span> <span class="p">(</span><span class="nb">hash</span> <span class="o">&amp;</span> <span class="n">M</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">hash_</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="p">:</span>
        <span class="n">hash_</span> <span class="o">==</span> <span class="o">-</span><span class="mi">2</span>
    <span class="k">return</span> <span class="n">hash_</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="iterator-types">
<span id="typeiter"></span><h2>4.5. Iterator Types<a class="headerlink" href="#iterator-types" title="Permalink to this headline">¶</a></h2>
<p id="index-18">Python supports a concept of iteration over containers.  This is implemented
using two distinct methods; these are used to allow user-defined classes to
support iteration.  Sequences, described below in more detail, always support
the iteration methods.</p>
<p>One method needs to be defined for container objects to provide iteration
support:</p>
<dl class="method">
<dt id="container.__iter__">
<tt class="descclassname">container.</tt><tt class="descname">__iter__</tt><big>(</big><big>)</big><a class="headerlink" href="#container.__iter__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator object.  The object is required to support the iterator
protocol described below.  If a container supports different types of
iteration, additional methods can be provided to specifically request
iterators for those iteration types.  (An example of an object supporting
multiple forms of iteration would be a tree structure which supports both
breadth-first and depth-first traversal.)  This method corresponds to the
<tt class="xref py py-attr docutils literal"><span class="pre">tp_iter</span></tt> slot of the type structure for Python objects in the Python/C
API.</p>
</dd></dl>

<p>The iterator objects themselves are required to support the following two
methods, which together form the <em class="dfn">iterator protocol</em>:</p>
<dl class="method">
<dt id="iterator.__iter__">
<tt class="descclassname">iterator.</tt><tt class="descname">__iter__</tt><big>(</big><big>)</big><a class="headerlink" href="#iterator.__iter__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the iterator object itself.  This is required to allow both containers
and iterators to be used with the <a class="reference internal" href="../reference/compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a> and <a class="reference internal" href="../reference/expressions.html#in"><tt class="xref std std-keyword docutils literal"><span class="pre">in</span></tt></a> statements.
This method corresponds to the <tt class="xref py py-attr docutils literal"><span class="pre">tp_iter</span></tt> slot of the type structure for
Python objects in the Python/C API.</p>
</dd></dl>

<dl class="method">
<dt id="iterator.__next__">
<tt class="descclassname">iterator.</tt><tt class="descname">__next__</tt><big>(</big><big>)</big><a class="headerlink" href="#iterator.__next__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the next item from the container.  If there are no further items, raise
the <a class="reference internal" href="exceptions.html#StopIteration" title="StopIteration"><tt class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></tt></a> exception.  This method corresponds to the
<tt class="xref py py-attr docutils literal"><span class="pre">tp_iternext</span></tt> slot of the type structure for Python objects in the
Python/C API.</p>
</dd></dl>

<p>Python defines several iterator objects to support iteration over general and
specific sequence types, dictionaries, and other more specialized forms.  The
specific types are not important beyond their implementation of the iterator
protocol.</p>
<p>Once an iterator&#8217;s <tt class="xref py py-meth docutils literal"><span class="pre">__next__()</span></tt> method raises <a class="reference internal" href="exceptions.html#StopIteration" title="StopIteration"><tt class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></tt></a>, it must
continue to do so on subsequent calls.  Implementations that do not obey this
property are deemed broken.</p>
<div class="section" id="generator-types">
<span id="id3"></span><h3>4.5.1. Generator Types<a class="headerlink" href="#generator-types" title="Permalink to this headline">¶</a></h3>
<p>Python&#8217;s <a class="reference internal" href="../glossary.html#term-generator"><em class="xref std std-term">generator</em></a>s provide a convenient way to implement the iterator
protocol.  If a container object&#8217;s <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><tt class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></tt></a> method is implemented as a
generator, it will automatically return an iterator object (technically, a
generator object) supplying the <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><tt class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></tt></a> and <tt class="xref py py-meth docutils literal"><span class="pre">__next__()</span></tt> methods.
More information about generators can be found in <a class="reference internal" href="../reference/expressions.html#yieldexpr"><em>the documentation for
the yield expression</em></a>.</p>
</div>
</div>
<div class="section" id="sequence-types-list-tuple-range">
<span id="typesseq"></span><h2>4.6. Sequence Types &#8212; <a class="reference internal" href="#list" title="list"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a>, <a class="reference internal" href="#tuple" title="tuple"><tt class="xref py py-class docutils literal"><span class="pre">tuple</span></tt></a>, <a class="reference internal" href="#range" title="range"><tt class="xref py py-class docutils literal"><span class="pre">range</span></tt></a><a class="headerlink" href="#sequence-types-list-tuple-range" title="Permalink to this headline">¶</a></h2>
<p>There are three basic sequence types: lists, tuples, and range objects.
Additional sequence types tailored for processing of
<a class="reference internal" href="#binaryseq"><em>binary data</em></a> and <a class="reference internal" href="#textseq"><em>text strings</em></a> are
described in dedicated sections.</p>
<div class="section" id="common-sequence-operations">
<span id="typesseq-common"></span><h3>4.6.1. Common Sequence Operations<a class="headerlink" href="#common-sequence-operations" title="Permalink to this headline">¶</a></h3>
<p id="index-19">The operations in the following table are supported by most sequence types,
both mutable and immutable. The <a class="reference internal" href="collections.abc.html#collections.abc.Sequence" title="collections.abc.Sequence"><tt class="xref py py-class docutils literal"><span class="pre">collections.abc.Sequence</span></tt></a> ABC is
provided to make it easier to correctly implement these operations on
custom sequence types.</p>
<p>This table lists the sequence operations sorted in ascending priority
(operations in the same box have the same priority).  In the table, <em>s</em> and <em>t</em>
are sequences of the same type, <em>n</em>, <em>i</em>, <em>j</em> and <em>k</em> are integers and <em>x</em> is
an arbitrary object that meets any type and value restrictions imposed by <em>s</em>.</p>
<p>The <tt class="docutils literal"><span class="pre">in</span></tt> and <tt class="docutils literal"><span class="pre">not</span> <span class="pre">in</span></tt> operations have the same priorities as the
comparison operations. The <tt class="docutils literal"><span class="pre">+</span></tt> (concatenation) and <tt class="docutils literal"><span class="pre">*</span></tt> (repetition)
operations have the same priority as the corresponding numeric operations.</p>
<table border="1" class="docutils" id="index-20">
<colgroup>
<col width="38%" />
<col width="47%" />
<col width="15%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Operation</th>
<th class="head">Result</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">s</span></tt></td>
<td><tt class="xref docutils literal"><span class="pre">True</span></tt> if an item of <em>s</em> is
equal to <em>x</em>, else <tt class="xref docutils literal"><span class="pre">False</span></tt></td>
<td>(1)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">x</span> <span class="pre">not</span> <span class="pre">in</span> <span class="pre">s</span></tt></td>
<td><tt class="xref docutils literal"><span class="pre">False</span></tt> if an item of <em>s</em> is
equal to <em>x</em>, else <tt class="xref docutils literal"><span class="pre">True</span></tt></td>
<td>(1)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s</span> <span class="pre">+</span> <span class="pre">t</span></tt></td>
<td>the concatenation of <em>s</em> and
<em>t</em></td>
<td>(6)(7)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s</span> <span class="pre">*</span> <span class="pre">n</span></tt> or
<tt class="docutils literal"><span class="pre">n</span> <span class="pre">*</span> <span class="pre">s</span></tt></td>
<td><em>n</em> shallow copies of <em>s</em>
concatenated</td>
<td>(2)(7)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s[i]</span></tt></td>
<td><em>i</em>th item of <em>s</em>, origin 0</td>
<td>(3)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s[i:j]</span></tt></td>
<td>slice of <em>s</em> from <em>i</em> to <em>j</em></td>
<td>(3)(4)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s[i:j:k]</span></tt></td>
<td>slice of <em>s</em> from <em>i</em> to <em>j</em>
with step <em>k</em></td>
<td>(3)(5)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">len(s)</span></tt></td>
<td>length of <em>s</em></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">min(s)</span></tt></td>
<td>smallest item of <em>s</em></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">max(s)</span></tt></td>
<td>largest item of <em>s</em></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s.index(x[,</span> <span class="pre">i[,</span> <span class="pre">j]])</span></tt></td>
<td>index of the first occurence
of <em>x</em> in <em>s</em> (at or after
index <em>i</em> and before index <em>j</em>)</td>
<td>(8)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s.count(x)</span></tt></td>
<td>total number of occurences of
<em>x</em> in <em>s</em></td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
<p>Sequences of the same type also support comparisons.  In particular, tuples
and lists are compared lexicographically by comparing corresponding elements.
This means that to compare equal, every element must compare equal and the
two sequences must be of the same type and have the same length.  (For full
details see <a class="reference internal" href="../reference/expressions.html#comparisons"><em>Comparisons</em></a> in the language reference.)</p>
<p>Notes:</p>
<ol class="arabic">
<li><p class="first">While the <tt class="docutils literal"><span class="pre">in</span></tt> and <tt class="docutils literal"><span class="pre">not</span> <span class="pre">in</span></tt> operations are used only for simple
containment testing in the general case, some specialised sequences
(such as <a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-class docutils literal"><span class="pre">str</span></tt></a>, <a class="reference internal" href="functions.html#bytes" title="bytes"><tt class="xref py py-class docutils literal"><span class="pre">bytes</span></tt></a> and <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a>) also use
them for subsequence testing:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="s">&quot;gg&quot;</span> <span class="ow">in</span> <span class="s">&quot;eggs&quot;</span>
<span class="go">True</span>
</pre></div>
</div>
</li>
<li><p class="first">Values of <em>n</em> less than <tt class="docutils literal"><span class="pre">0</span></tt> are treated as <tt class="docutils literal"><span class="pre">0</span></tt> (which yields an empty
sequence of the same type as <em>s</em>).  Note also that the copies are shallow;
nested structures are not copied.  This often haunts new Python programmers;
consider:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span> <span class="o">=</span> <span class="p">[[]]</span> <span class="o">*</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span>
<span class="go">[[], [], []]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span>
<span class="go">[[3], [3], [3]]</span>
</pre></div>
</div>
<p>What has happened is that <tt class="docutils literal"><span class="pre">[[]]</span></tt> is a one-element list containing an empty
list, so all three elements of <tt class="docutils literal"><span class="pre">[[]]</span> <span class="pre">*</span> <span class="pre">3</span></tt> are (pointers to) this single empty
list.  Modifying any of the elements of <tt class="docutils literal"><span class="pre">lists</span></tt> modifies this single list.
You can create a list of different lists this way:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span> <span class="o">=</span> <span class="p">[[]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span>
<span class="go">[[3], [5], [7]]</span>
</pre></div>
</div>
</li>
<li><p class="first">If <em>i</em> or <em>j</em> is negative, the index is relative to the end of the string:
<tt class="docutils literal"><span class="pre">len(s)</span> <span class="pre">+</span> <span class="pre">i</span></tt> or <tt class="docutils literal"><span class="pre">len(s)</span> <span class="pre">+</span> <span class="pre">j</span></tt> is substituted.  But note that <tt class="docutils literal"><span class="pre">-0</span></tt> is
still <tt class="docutils literal"><span class="pre">0</span></tt>.</p>
</li>
<li><p class="first">The slice of <em>s</em> from <em>i</em> to <em>j</em> is defined as the sequence of items with index
<em>k</em> such that <tt class="docutils literal"><span class="pre">i</span> <span class="pre">&lt;=</span> <span class="pre">k</span> <span class="pre">&lt;</span> <span class="pre">j</span></tt>.  If <em>i</em> or <em>j</em> is greater than <tt class="docutils literal"><span class="pre">len(s)</span></tt>, use
<tt class="docutils literal"><span class="pre">len(s)</span></tt>.  If <em>i</em> is omitted or <tt class="xref docutils literal"><span class="pre">None</span></tt>, use <tt class="docutils literal"><span class="pre">0</span></tt>.  If <em>j</em> is omitted or
<tt class="xref docutils literal"><span class="pre">None</span></tt>, use <tt class="docutils literal"><span class="pre">len(s)</span></tt>.  If <em>i</em> is greater than or equal to <em>j</em>, the slice is
empty.</p>
</li>
<li><p class="first">The slice of <em>s</em> from <em>i</em> to <em>j</em> with step <em>k</em> is defined as the sequence of
items with index  <tt class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">i</span> <span class="pre">+</span> <span class="pre">n*k</span></tt> such that <tt class="docutils literal"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">n</span> <span class="pre">&lt;</span> <span class="pre">(j-i)/k</span></tt>.  In other words,
the indices are <tt class="docutils literal"><span class="pre">i</span></tt>, <tt class="docutils literal"><span class="pre">i+k</span></tt>, <tt class="docutils literal"><span class="pre">i+2*k</span></tt>, <tt class="docutils literal"><span class="pre">i+3*k</span></tt> and so on, stopping when
<em>j</em> is reached (but never including <em>j</em>).  If <em>i</em> or <em>j</em> is greater than
<tt class="docutils literal"><span class="pre">len(s)</span></tt>, use <tt class="docutils literal"><span class="pre">len(s)</span></tt>.  If <em>i</em> or <em>j</em> are omitted or <tt class="xref docutils literal"><span class="pre">None</span></tt>, they become
&#8220;end&#8221; values (which end depends on the sign of <em>k</em>).  Note, <em>k</em> cannot be zero.
If <em>k</em> is <tt class="xref docutils literal"><span class="pre">None</span></tt>, it is treated like <tt class="docutils literal"><span class="pre">1</span></tt>.</p>
</li>
<li><p class="first">Concatenating immutable sequences always results in a new object.  This
means that building up a sequence by repeated concatenation will have a
quadratic runtime cost in the total sequence length.  To get a linear
runtime cost, you must switch to one of the alternatives below:</p>
<ul class="simple">
<li>if concatenating <a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-class docutils literal"><span class="pre">str</span></tt></a> objects, you can build a list and use
<a class="reference internal" href="#str.join" title="str.join"><tt class="xref py py-meth docutils literal"><span class="pre">str.join()</span></tt></a> at the end or else write to a <a class="reference internal" href="io.html#io.StringIO" title="io.StringIO"><tt class="xref py py-class docutils literal"><span class="pre">io.StringIO</span></tt></a>
instance and retrieve its value when complete</li>
<li>if concatenating <a class="reference internal" href="functions.html#bytes" title="bytes"><tt class="xref py py-class docutils literal"><span class="pre">bytes</span></tt></a> objects, you can similarly use
<tt class="xref py py-meth docutils literal"><span class="pre">bytes.join()</span></tt> or <a class="reference internal" href="io.html#io.BytesIO" title="io.BytesIO"><tt class="xref py py-class docutils literal"><span class="pre">io.BytesIO</span></tt></a>, or you can do in-place
concatenation with a <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a> object.  <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a>
objects are mutable and have an efficient overallocation mechanism</li>
<li>if concatenating <a class="reference internal" href="#tuple" title="tuple"><tt class="xref py py-class docutils literal"><span class="pre">tuple</span></tt></a> objects, extend a <a class="reference internal" href="#list" title="list"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a> instead</li>
<li>for other types, investigate the relevant class documentation</li>
</ul>
</li>
<li><p class="first">Some sequence types (such as <a class="reference internal" href="#range" title="range"><tt class="xref py py-class docutils literal"><span class="pre">range</span></tt></a>) only support item sequences
that follow specific patterns, and hence don&#8217;t support sequence
concatenation or repetition.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">index</span></tt> raises <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> when <em>x</em> is not found in <em>s</em>.
When supported, the additional arguments to the index method allow
efficient searching of subsections of the sequence. Passing the extra
arguments is roughly equivalent to using <tt class="docutils literal"><span class="pre">s[i:j].index(x)</span></tt>, only
without copying any data and with the returned index being relative to
the start of the sequence rather than the start of the slice.</p>
</li>
</ol>
</div>
<div class="section" id="immutable-sequence-types">
<span id="typesseq-immutable"></span><h3>4.6.2. Immutable Sequence Types<a class="headerlink" href="#immutable-sequence-types" title="Permalink to this headline">¶</a></h3>
<p id="index-21">The only operation that immutable sequence types generally implement that is
not also implemented by mutable sequence types is support for the <a class="reference internal" href="functions.html#hash" title="hash"><tt class="xref py py-func docutils literal"><span class="pre">hash()</span></tt></a>
built-in.</p>
<p>This support allows immutable sequences, such as <a class="reference internal" href="#tuple" title="tuple"><tt class="xref py py-class docutils literal"><span class="pre">tuple</span></tt></a> instances, to
be used as <a class="reference internal" href="#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> keys and stored in <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> and <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a>
instances.</p>
<p>Attempting to hash an immutable sequence that contains unhashable values will
result in <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a>.</p>
</div>
<div class="section" id="mutable-sequence-types">
<span id="typesseq-mutable"></span><h3>4.6.3. Mutable Sequence Types<a class="headerlink" href="#mutable-sequence-types" title="Permalink to this headline">¶</a></h3>
<p id="index-22">The operations in the following table are defined on mutable sequence types.
The <a class="reference internal" href="collections.abc.html#collections.abc.MutableSequence" title="collections.abc.MutableSequence"><tt class="xref py py-class docutils literal"><span class="pre">collections.abc.MutableSequence</span></tt></a> ABC is provided to make it
easier to correctly implement these operations on custom sequence types.</p>
<p>In the table <em>s</em> is an instance of a mutable sequence type, <em>t</em> is any
iterable object and <em>x</em> is an arbitrary object that meets any type
and value restrictions imposed by <em>s</em> (for example, <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a> only
accepts integers that meet the value restriction <tt class="docutils literal"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">x</span> <span class="pre">&lt;=</span> <span class="pre">255</span></tt>).</p>
<table border="1" class="docutils" id="index-23">
<colgroup>
<col width="36%" />
<col width="39%" />
<col width="25%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Operation</th>
<th class="head">Result</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><tt class="docutils literal"><span class="pre">s[i]</span> <span class="pre">=</span> <span class="pre">x</span></tt></td>
<td>item <em>i</em> of <em>s</em> is replaced by
<em>x</em></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s[i:j]</span> <span class="pre">=</span> <span class="pre">t</span></tt></td>
<td>slice of <em>s</em> from <em>i</em> to <em>j</em>
is replaced by the contents of
the iterable <em>t</em></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">del</span> <span class="pre">s[i:j]</span></tt></td>
<td>same as <tt class="docutils literal"><span class="pre">s[i:j]</span> <span class="pre">=</span> <span class="pre">[]</span></tt></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s[i:j:k]</span> <span class="pre">=</span> <span class="pre">t</span></tt></td>
<td>the elements of <tt class="docutils literal"><span class="pre">s[i:j:k]</span></tt>
are replaced by those of <em>t</em></td>
<td>(1)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">del</span> <span class="pre">s[i:j:k]</span></tt></td>
<td>removes the elements of
<tt class="docutils literal"><span class="pre">s[i:j:k]</span></tt> from the list</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s.append(x)</span></tt></td>
<td>appends <em>x</em> to the end of the
sequence (same as
<tt class="docutils literal"><span class="pre">s[len(s):len(s)]</span> <span class="pre">=</span> <span class="pre">[x]</span></tt>)</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s.clear()</span></tt></td>
<td>removes all items from <tt class="docutils literal"><span class="pre">s</span></tt>
(same as <tt class="docutils literal"><span class="pre">del</span> <span class="pre">s[:]</span></tt>)</td>
<td>(5)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s.copy()</span></tt></td>
<td>creates a shallow copy of <tt class="docutils literal"><span class="pre">s</span></tt>
(same as <tt class="docutils literal"><span class="pre">s[:]</span></tt>)</td>
<td>(5)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s.extend(t)</span></tt></td>
<td>extends <em>s</em> with the
contents of <em>t</em> (same as
<tt class="docutils literal"><span class="pre">s[len(s):len(s)]</span> <span class="pre">=</span> <span class="pre">t</span></tt>)</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s.insert(i,</span> <span class="pre">x)</span></tt></td>
<td>inserts <em>x</em> into <em>s</em> at the
index given by <em>i</em>
(same as <tt class="docutils literal"><span class="pre">s[i:i]</span> <span class="pre">=</span> <span class="pre">[x]</span></tt>)</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s.pop([i])</span></tt></td>
<td>retrieves the item at <em>i</em> and
also removes it from <em>s</em></td>
<td>(2)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s.remove(x)</span></tt></td>
<td>remove the first item from <em>s</em>
where <tt class="docutils literal"><span class="pre">s[i]</span> <span class="pre">==</span> <span class="pre">x</span></tt></td>
<td>(3)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">s.reverse()</span></tt></td>
<td>reverses the items of <em>s</em> in
place</td>
<td>(4)</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic">
<li><p class="first"><em>t</em> must have the same length as the slice it is replacing.</p>
</li>
<li><p class="first">The optional argument <em>i</em> defaults to <tt class="docutils literal"><span class="pre">-1</span></tt>, so that by default the last
item is removed and returned.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">remove</span></tt> raises <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> when <em>x</em> is not found in <em>s</em>.</p>
</li>
<li><p class="first">The <tt class="xref py py-meth docutils literal"><span class="pre">reverse()</span></tt> method modifies the sequence in place for economy of
space when reversing a large sequence.  To remind users that it operates by
side effect, it does not return the reversed sequence.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">clear()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">copy()</span></tt> are included for consistency with the
interfaces of mutable containers that don&#8217;t support slicing operations
(such as <a class="reference internal" href="#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> and <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a>)</p>
<p class="versionadded">
<span class="versionmodified">New in version 3.3:</span> <tt class="xref py py-meth docutils literal"><span class="pre">clear()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">copy()</span></tt> methods.</p>
</li>
</ol>
</div>
<div class="section" id="lists">
<span id="typesseq-list"></span><h3>4.6.4. Lists<a class="headerlink" href="#lists" title="Permalink to this headline">¶</a></h3>
<p id="index-24">Lists are mutable sequences, typically used to store collections of
homogeneous items (where the precise degree of similarity will vary by
application).</p>
<dl class="class">
<dt id="list">
<em class="property">class </em><tt class="descname">list</tt><big>(</big><span class="optional">[</span><em>iterable</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#list" title="Permalink to this definition">¶</a></dt>
<dd><p>Lists may be constructed in several ways:</p>
<ul class="simple">
<li>Using a pair of square brackets to denote the empty list: <tt class="docutils literal"><span class="pre">[]</span></tt></li>
<li>Using square brackets, separating items with commas: <tt class="docutils literal"><span class="pre">[a]</span></tt>, <tt class="docutils literal"><span class="pre">[a,</span> <span class="pre">b,</span> <span class="pre">c]</span></tt></li>
<li>Using a list comprehension: <tt class="docutils literal"><span class="pre">[x</span> <span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">iterable]</span></tt></li>
<li>Using the type constructor: <tt class="docutils literal"><span class="pre">list()</span></tt> or <tt class="docutils literal"><span class="pre">list(iterable)</span></tt></li>
</ul>
<p>The constructor builds a list whose items are the same and in the same
order as <em>iterable</em>&#8216;s items.  <em>iterable</em> may be either a sequence, a
container that supports iteration, or an iterator object.  If <em>iterable</em>
is already a list, a copy is made and returned, similar to <tt class="docutils literal"><span class="pre">iterable[:]</span></tt>.
For example, <tt class="docutils literal"><span class="pre">list('abc')</span></tt> returns <tt class="docutils literal"><span class="pre">['a',</span> <span class="pre">'b',</span> <span class="pre">'c']</span></tt> and
<tt class="docutils literal"><span class="pre">list(</span> <span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">3)</span> <span class="pre">)</span></tt> returns <tt class="docutils literal"><span class="pre">[1,</span> <span class="pre">2,</span> <span class="pre">3]</span></tt>.
If no argument is given, the constructor creates a new empty list, <tt class="docutils literal"><span class="pre">[]</span></tt>.</p>
<p>Many other operations also produce lists, including the <a class="reference internal" href="functions.html#sorted" title="sorted"><tt class="xref py py-func docutils literal"><span class="pre">sorted()</span></tt></a>
built-in.</p>
<p>Lists implement all of the <a class="reference internal" href="#typesseq-common"><em>common</em></a> and
<a class="reference internal" href="#typesseq-mutable"><em>mutable</em></a> sequence operations. Lists also provide the
following additional method:</p>
<dl class="method">
<dt id="list.sort">
<tt class="descname">sort</tt><big>(</big><em>*</em>, <em>key=None</em>, <em>reverse=None</em><big>)</big><a class="headerlink" href="#list.sort" title="Permalink to this definition">¶</a></dt>
<dd><p>This method sorts the list in place, using only <tt class="docutils literal"><span class="pre">&lt;</span></tt> comparisons
between items. Exceptions are not suppressed - if any comparison operations
fail, the entire sort operation will fail (and the list will likely be left
in a partially modified state).</p>
<p><em>key</em> specifies a function of one argument that is used to extract a
comparison key from each list element (for example, <tt class="docutils literal"><span class="pre">key=str.lower</span></tt>).
The key corresponding to each item in the list is calculated once and
then used for the entire sorting process. The default value of <tt class="xref docutils literal"><span class="pre">None</span></tt>
means that list items are sorted directly without calculating a separate
key value.</p>
<p>The <a class="reference internal" href="functools.html#functools.cmp_to_key" title="functools.cmp_to_key"><tt class="xref py py-func docutils literal"><span class="pre">functools.cmp_to_key()</span></tt></a> utility is available to convert a 2.x
style <em>cmp</em> function to a <em>key</em> function.</p>
<p><em>reverse</em> is a boolean value.  If set to <tt class="xref docutils literal"><span class="pre">True</span></tt>, then the list elements
are sorted as if each comparison were reversed.</p>
<p>This method modifies the sequence in place for economy of space when
sorting a large sequence.  To remind users that it operates by side
effect, it does not return the sorted sequence (use <a class="reference internal" href="functions.html#sorted" title="sorted"><tt class="xref py py-func docutils literal"><span class="pre">sorted()</span></tt></a> to
explicitly request a new sorted list instance).</p>
<p>The <a class="reference internal" href="#list.sort" title="list.sort"><tt class="xref py py-meth docutils literal"><span class="pre">sort()</span></tt></a> method is guaranteed to be stable.  A sort is stable if it
guarantees not to change the relative order of elements that compare equal
&#8212; this is helpful for sorting in multiple passes (for example, sort by
department, then by salary grade).</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> While a list is being sorted, the effect of attempting to mutate, or even
inspect, the list is undefined.  The C implementation of Python makes the
list appear empty for the duration, and raises <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> if it can
detect that the list has been mutated during a sort.</p>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="tuples">
<span id="typesseq-tuple"></span><h3>4.6.5. Tuples<a class="headerlink" href="#tuples" title="Permalink to this headline">¶</a></h3>
<p id="index-25">Tuples are immutable sequences, typically used to store collections of
heterogeneous data (such as the 2-tuples produced by the <a class="reference internal" href="functions.html#enumerate" title="enumerate"><tt class="xref py py-func docutils literal"><span class="pre">enumerate()</span></tt></a>
built-in). Tuples are also used for cases where an immutable sequence of
homogeneous data is needed (such as allowing storage in a <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> or
<a class="reference internal" href="#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> instance).</p>
<dl class="class">
<dt id="tuple">
<em class="property">class </em><tt class="descname">tuple</tt><big>(</big><span class="optional">[</span><em>iterable</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#tuple" title="Permalink to this definition">¶</a></dt>
<dd><p>Tuples may be constructed in a number of ways:</p>
<ul class="simple">
<li>Using a pair of parentheses to denote the empty tuple: <tt class="docutils literal"><span class="pre">()</span></tt></li>
<li>Using a trailing comma for a singleton tuple: <tt class="docutils literal"><span class="pre">a,</span></tt> or <tt class="docutils literal"><span class="pre">(a,)</span></tt></li>
<li>Separating items with commas: <tt class="docutils literal"><span class="pre">a,</span> <span class="pre">b,</span> <span class="pre">c</span></tt> or <tt class="docutils literal"><span class="pre">(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></tt></li>
<li>Using the <a class="reference internal" href="#tuple" title="tuple"><tt class="xref py py-func docutils literal"><span class="pre">tuple()</span></tt></a> built-in: <tt class="docutils literal"><span class="pre">tuple()</span></tt> or <tt class="docutils literal"><span class="pre">tuple(iterable)</span></tt></li>
</ul>
<p>The constructor builds a tuple whose items are the same and in the same
order as <em>iterable</em>&#8216;s items.  <em>iterable</em> may be either a sequence, a
container that supports iteration, or an iterator object.  If <em>iterable</em>
is already a tuple, it is returned unchanged. For example,
<tt class="docutils literal"><span class="pre">tuple('abc')</span></tt> returns <tt class="docutils literal"><span class="pre">('a',</span> <span class="pre">'b',</span> <span class="pre">'c')</span></tt> and
<tt class="docutils literal"><span class="pre">tuple(</span> <span class="pre">[1,</span> <span class="pre">2,</span> <span class="pre">3]</span> <span class="pre">)</span></tt> returns <tt class="docutils literal"><span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">3)</span></tt>.
If no argument is given, the constructor creates a new empty tuple, <tt class="docutils literal"><span class="pre">()</span></tt>.</p>
<p>Note that it is actually the comma which makes a tuple, not the parentheses.
The parentheses are optional, except in the empty tuple case, or
when they are needed to avoid syntactic ambiguity. For example,
<tt class="docutils literal"><span class="pre">f(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></tt> is a function call with three arguments, while
<tt class="docutils literal"><span class="pre">f((a,</span> <span class="pre">b,</span> <span class="pre">c))</span></tt> is a function call with a 3-tuple as the sole argument.</p>
<p>Tuples implement all of the <a class="reference internal" href="#typesseq-common"><em>common</em></a> sequence
operations.</p>
</dd></dl>

<p>For heterogeneous collections of data where access by name is clearer than
access by index, <a class="reference internal" href="collections.html#collections.namedtuple" title="collections.namedtuple"><tt class="xref py py-func docutils literal"><span class="pre">collections.namedtuple()</span></tt></a> may be a more appropriate
choice than a simple tuple object.</p>
</div>
<div class="section" id="ranges">
<span id="typesseq-range"></span><h3>4.6.6. Ranges<a class="headerlink" href="#ranges" title="Permalink to this headline">¶</a></h3>
<p id="index-26">The <a class="reference internal" href="#range" title="range"><tt class="xref py py-class docutils literal"><span class="pre">range</span></tt></a> type represents an immutable sequence of numbers and is
commonly used for looping a specific number of times in <a class="reference internal" href="../reference/compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a>
loops.</p>
<dl class="class">
<dt id="range">
<em class="property">class </em><tt class="descname">range</tt><big>(</big><span class="optional">[</span><em>start</em><span class="optional">]</span>, <em>stop</em><span class="optional">[</span>, <em>step</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#range" title="Permalink to this definition">¶</a></dt>
<dd><p>The arguments to the range constructor must be integers (either built-in
<a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a> or any object that implements the <tt class="docutils literal"><span class="pre">__index__</span></tt> special
method).  If the <em>step</em> argument is omitted, it defaults to <tt class="docutils literal"><span class="pre">1</span></tt>.
If the <em>start</em> argument is omitted, it defaults to <tt class="docutils literal"><span class="pre">0</span></tt>.
If <em>step</em> is zero, <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> is raised.</p>
<p>For a positive <em>step</em>, the contents of a range <tt class="docutils literal"><span class="pre">r</span></tt> are determined by the
formula <tt class="docutils literal"><span class="pre">r[i]</span> <span class="pre">=</span> <span class="pre">start</span> <span class="pre">+</span> <span class="pre">step*i</span></tt> where <tt class="docutils literal"><span class="pre">i</span> <span class="pre">&gt;=</span> <span class="pre">0</span></tt> and
<tt class="docutils literal"><span class="pre">r[i]</span> <span class="pre">&lt;</span> <span class="pre">stop</span></tt>.</p>
<p>For a negative <em>step</em>, the contents of the range are still determined by
the formula <tt class="docutils literal"><span class="pre">r[i]</span> <span class="pre">=</span> <span class="pre">start</span> <span class="pre">+</span> <span class="pre">step*i</span></tt>, but the constraints are <tt class="docutils literal"><span class="pre">i</span> <span class="pre">&gt;=</span> <span class="pre">0</span></tt>
and <tt class="docutils literal"><span class="pre">r[i]</span> <span class="pre">&gt;</span> <span class="pre">stop</span></tt>.</p>
<p>A range object will be empty if <tt class="docutils literal"><span class="pre">r[0]</span></tt> does not meant the value
constraint. Ranges do support negative indices, but these are interpreted
as indexing from the end of the sequence determined by the positive
indices.</p>
<p>Ranges containing absolute values larger than <a class="reference internal" href="sys.html#sys.maxsize" title="sys.maxsize"><tt class="xref py py-data docutils literal"><span class="pre">sys.maxsize</span></tt></a> are
permitted but some features (such as <a class="reference internal" href="functions.html#len" title="len"><tt class="xref py py-func docutils literal"><span class="pre">len()</span></tt></a>) may raise
<a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><tt class="xref py py-exc docutils literal"><span class="pre">OverflowError</span></tt></a>.</p>
<p>Range examples:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
<span class="go">[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">))</span>
<span class="go">[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">5</span><span class="p">))</span>
<span class="go">[0, 5, 10, 15, 20, 25]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span>
<span class="go">[0, 3, 6, 9]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="o">-</span><span class="mi">10</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">))</span>
<span class="go">[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">))</span>
<span class="go">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span>
<span class="go">[]</span>
</pre></div>
</div>
<p>Ranges implement all of the <a class="reference internal" href="#typesseq-common"><em>common</em></a> sequence operations
except concatenation and repetition (due to the fact that range objects can
only represent sequences that follow a strict pattern and repetition and
concatenation will usually violate that pattern).</p>
</dd></dl>

<p>The advantage of the <a class="reference internal" href="#range" title="range"><tt class="xref py py-class docutils literal"><span class="pre">range</span></tt></a> type over a regular <a class="reference internal" href="#list" title="list"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a> or
<a class="reference internal" href="#tuple" title="tuple"><tt class="xref py py-class docutils literal"><span class="pre">tuple</span></tt></a> is that a <a class="reference internal" href="#range" title="range"><tt class="xref py py-class docutils literal"><span class="pre">range</span></tt></a> object will always take the same
(small) amount of memory, no matter the size of the range it represents (as it
only stores the <tt class="docutils literal"><span class="pre">start</span></tt>, <tt class="docutils literal"><span class="pre">stop</span></tt> and <tt class="docutils literal"><span class="pre">step</span></tt> values, calculating individual
items and subranges as needed).</p>
<p>Range objects implement the <tt class="xref py py-class docutils literal"><span class="pre">collections.Sequence</span></tt> ABC, and provide
features such as containment tests, element index lookup, slicing and
support for negative indices (see <a class="reference internal" href="#typesseq"><em>Sequence Types &#8212; list, tuple, range</em></a>):</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">r</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span>
<span class="go">range(0, 20, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">11</span> <span class="ow">in</span> <span class="n">r</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">10</span> <span class="ow">in</span> <span class="n">r</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span><span class="p">[</span><span class="mi">5</span><span class="p">]</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span><span class="p">[:</span><span class="mi">5</span><span class="p">]</span>
<span class="go">range(0, 10, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="go">18</span>
</pre></div>
</div>
<p>Testing range objects for equality with <tt class="docutils literal"><span class="pre">==</span></tt> and <tt class="docutils literal"><span class="pre">!=</span></tt> compares
them as sequences.  That is, two range objects are considered equal if
they represent the same sequence of values.  (Note that two range
objects that compare equal might have different <tt class="xref py py-attr docutils literal"><span class="pre">start</span></tt>,
<tt class="xref py py-attr docutils literal"><span class="pre">stop</span></tt> and <tt class="xref py py-attr docutils literal"><span class="pre">step</span></tt> attributes, for example <tt class="docutils literal"><span class="pre">range(0)</span> <span class="pre">==</span>
<span class="pre">range(2,</span> <span class="pre">1,</span> <span class="pre">3)</span></tt> or <tt class="docutils literal"><span class="pre">range(0,</span> <span class="pre">3,</span> <span class="pre">2)</span> <span class="pre">==</span> <span class="pre">range(0,</span> <span class="pre">4,</span> <span class="pre">2)</span></tt>.)</p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 3.2:</span> Implement the Sequence ABC.
Support slicing and negative indices.
Test <a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a> objects for membership in constant time instead of
iterating through all items.</p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 3.3:</span> Define &#8216;==&#8217; and &#8216;!=&#8217; to compare range objects based on the
sequence of values they define (instead of comparing based on
object identity).</p>
<p class="versionadded">
<span class="versionmodified">New in version 3.3:</span> The <tt class="xref py py-attr docutils literal"><span class="pre">start</span></tt>, <tt class="xref py py-attr docutils literal"><span class="pre">stop</span></tt> and <tt class="xref py py-attr docutils literal"><span class="pre">step</span></tt> attributes.</p>
</div>
</div>
<div class="section" id="text-sequence-type-str">
<span id="textseq"></span><h2>4.7. Text Sequence Type &#8212; <a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-class docutils literal"><span class="pre">str</span></tt></a><a class="headerlink" href="#text-sequence-type-str" title="Permalink to this headline">¶</a></h2>
<p id="index-27">Textual data in Python is handled with <a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-class docutils literal"><span class="pre">str</span></tt></a> objects, which are
immutable sequences of Unicode code points.  String literals are
written in a variety of ways:</p>
<ul class="simple">
<li>Single quotes: <tt class="docutils literal"><span class="pre">'allows</span> <span class="pre">embedded</span> <span class="pre">&quot;double&quot;</span> <span class="pre">quotes'</span></tt></li>
<li>Double quotes: <tt class="docutils literal"><span class="pre">&quot;allows</span> <span class="pre">embedded</span> <span class="pre">'single'</span> <span class="pre">quotes&quot;</span></tt>.</li>
<li>Triple quoted: <tt class="docutils literal"><span class="pre">'''Three</span> <span class="pre">single</span> <span class="pre">quotes'''</span></tt>, <tt class="docutils literal"><span class="pre">&quot;&quot;&quot;Three</span> <span class="pre">double</span> <span class="pre">quotes&quot;&quot;&quot;</span></tt></li>
</ul>
<p>Triple quoted strings may span multiple lines - all associated whitespace will
be included in the string literal.</p>
<p>String literals that are part of a single expression and have only whitespace
between them will be implicitly converted to a single string literal. That
is, <tt class="docutils literal"><span class="pre">(&quot;spam</span> <span class="pre">&quot;</span> <span class="pre">&quot;eggs&quot;)</span> <span class="pre">==</span> <span class="pre">&quot;spam</span> <span class="pre">eggs&quot;</span></tt>.</p>
<p>See <a class="reference internal" href="../reference/lexical_analysis.html#strings"><em>String and Bytes literals</em></a> for more about the various forms of string literal,
including supported escape sequences, and the <tt class="docutils literal"><span class="pre">r</span></tt> (&#8220;raw&#8221;) prefix that
disables most escape sequence processing.</p>
<p>Strings may also be created from other objects with the <a class="reference internal" href="functions.html#func-str"><em>str</em></a>
built-in.</p>
<p>Since there is no separate &#8220;character&#8221; type, indexing a string produces
strings of length 1. That is, for a non-empty string <em>s</em>, <tt class="docutils literal"><span class="pre">s[0]</span> <span class="pre">==</span> <span class="pre">s[0:1]</span></tt>.</p>
<p>There is also no mutable string type, but <a class="reference internal" href="#str.join" title="str.join"><tt class="xref py py-meth docutils literal"><span class="pre">str.join()</span></tt></a> or
<a class="reference internal" href="io.html#io.StringIO" title="io.StringIO"><tt class="xref py py-class docutils literal"><span class="pre">io.StringIO</span></tt></a> can be used to efficiently construct strings from
multiple fragments.</p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 3.3:</span> For backwards compatibility with the Python 2 series, the <tt class="docutils literal"><span class="pre">u</span></tt> prefix is
once again permitted on string literals. It has no effect on the meaning
of string literals and cannot be combined with the <tt class="docutils literal"><span class="pre">r</span></tt> prefix.</p>
<div class="section" id="string-methods">
<span id="id4"></span><h3>4.7.1. String Methods<a class="headerlink" href="#string-methods" title="Permalink to this headline">¶</a></h3>
<p id="index-28">Strings implement all of the <a class="reference internal" href="#typesseq-common"><em>common</em></a> sequence
operations, along with the additional methods described below.</p>
<p>Strings also support two styles of string formatting, one providing a large
degree of flexibility and customization (see <a class="reference internal" href="#str.format" title="str.format"><tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt></a>,
<a class="reference internal" href="string.html#formatstrings"><em>Format String Syntax</em></a> and <a class="reference internal" href="string.html#string-formatting"><em>String Formatting</em></a>) and the other based on C
<tt class="docutils literal"><span class="pre">printf</span></tt> style formatting that handles a narrower range of types and is
slightly harder to use correctly, but is often faster for the cases it can
handle (<a class="reference internal" href="#old-string-formatting"><em>printf-style String Formatting</em></a>).</p>
<p>The <a class="reference internal" href="text.html#textservices"><em>Text Processing Services</em></a> section of the standard library covers a number of
other modules that provide various text related utilities (including regular
expression support in the <a class="reference internal" href="re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module).</p>
<dl class="method">
<dt id="str.capitalize">
<tt class="descclassname">str.</tt><tt class="descname">capitalize</tt><big>(</big><big>)</big><a class="headerlink" href="#str.capitalize" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with its first character capitalized and the
rest lowercased.</p>
</dd></dl>

<dl class="method">
<dt id="str.casefold">
<tt class="descclassname">str.</tt><tt class="descname">casefold</tt><big>(</big><big>)</big><a class="headerlink" href="#str.casefold" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a casefolded copy of the string. Casefolded strings may be used for
caseless matching.</p>
<p>Casefolding is similar to lowercasing but more aggressive because it is
intended to remove all case distinctions in a string. For example, the German
lowercase letter <tt class="docutils literal"><span class="pre">'ß'</span></tt> is equivalent to <tt class="docutils literal"><span class="pre">&quot;ss&quot;</span></tt>. Since it is already
lowercase, <a class="reference internal" href="#str.lower" title="str.lower"><tt class="xref py py-meth docutils literal"><span class="pre">lower()</span></tt></a> would do nothing to <tt class="docutils literal"><span class="pre">'ß'</span></tt>; <a class="reference internal" href="#str.casefold" title="str.casefold"><tt class="xref py py-meth docutils literal"><span class="pre">casefold()</span></tt></a>
converts it to <tt class="docutils literal"><span class="pre">&quot;ss&quot;</span></tt>.</p>
<p>The casefolding algorithm is described in section 3.13 of the Unicode
Standard.</p>
<p class="versionadded">
<span class="versionmodified">New in version 3.3.</span> </p>
</dd></dl>

<dl class="method">
<dt id="str.center">
<tt class="descclassname">str.</tt><tt class="descname">center</tt><big>(</big><em>width</em><span class="optional">[</span>, <em>fillchar</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.center" title="Permalink to this definition">¶</a></dt>
<dd><p>Return centered in a string of length <em>width</em>. Padding is done using the
specified <em>fillchar</em> (default is a space).</p>
</dd></dl>

<dl class="method">
<dt id="str.count">
<tt class="descclassname">str.</tt><tt class="descname">count</tt><big>(</big><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.count" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of non-overlapping occurrences of substring <em>sub</em> in the
range [<em>start</em>, <em>end</em>].  Optional arguments <em>start</em> and <em>end</em> are
interpreted as in slice notation.</p>
</dd></dl>

<dl class="method">
<dt id="str.encode">
<tt class="descclassname">str.</tt><tt class="descname">encode</tt><big>(</big><em>encoding=&quot;utf-8&quot;</em>, <em>errors=&quot;strict&quot;</em><big>)</big><a class="headerlink" href="#str.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an encoded version of the string as a bytes object. Default encoding
is <tt class="docutils literal"><span class="pre">'utf-8'</span></tt>. <em>errors</em> may be given to set a different error handling scheme.
The default for <em>errors</em> is <tt class="docutils literal"><span class="pre">'strict'</span></tt>, meaning that encoding errors raise
a <a class="reference internal" href="exceptions.html#UnicodeError" title="UnicodeError"><tt class="xref py py-exc docutils literal"><span class="pre">UnicodeError</span></tt></a>. Other possible
values are <tt class="docutils literal"><span class="pre">'ignore'</span></tt>, <tt class="docutils literal"><span class="pre">'replace'</span></tt>, <tt class="docutils literal"><span class="pre">'xmlcharrefreplace'</span></tt>,
<tt class="docutils literal"><span class="pre">'backslashreplace'</span></tt> and any other name registered via
<a class="reference internal" href="codecs.html#codecs.register_error" title="codecs.register_error"><tt class="xref py py-func docutils literal"><span class="pre">codecs.register_error()</span></tt></a>, see section <a class="reference internal" href="codecs.html#codec-base-classes"><em>Codec Base Classes</em></a>. For a
list of possible encodings, see section <a class="reference internal" href="codecs.html#standard-encodings"><em>Standard Encodings</em></a>.</p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 3.1:</span> Support for keyword arguments added.</p>
</dd></dl>

<dl class="method">
<dt id="str.endswith">
<tt class="descclassname">str.</tt><tt class="descname">endswith</tt><big>(</big><em>suffix</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.endswith" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <tt class="xref docutils literal"><span class="pre">True</span></tt> if the string ends with the specified <em>suffix</em>, otherwise return
<tt class="xref docutils literal"><span class="pre">False</span></tt>.  <em>suffix</em> can also be a tuple of suffixes to look for.  With optional
<em>start</em>, test beginning at that position.  With optional <em>end</em>, stop comparing
at that position.</p>
</dd></dl>

<dl class="method">
<dt id="str.expandtabs">
<tt class="descclassname">str.</tt><tt class="descname">expandtabs</tt><big>(</big><span class="optional">[</span><em>tabsize</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.expandtabs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string where all tab characters are replaced by zero or
more spaces, depending on the current column and the given tab size.  The
column number is reset to zero after each newline occurring in the string.
If <em>tabsize</em> is not given, a tab size of <tt class="docutils literal"><span class="pre">8</span></tt> characters is assumed.  This
doesn&#8217;t understand other non-printing characters or escape sequences.</p>
</dd></dl>

<dl class="method">
<dt id="str.find">
<tt class="descclassname">str.</tt><tt class="descname">find</tt><big>(</big><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.find" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the lowest index in the string where substring <em>sub</em> is found, such
that <em>sub</em> is contained in the slice <tt class="docutils literal"><span class="pre">s[start:end]</span></tt>.  Optional arguments
<em>start</em> and <em>end</em> are interpreted as in slice notation.  Return <tt class="docutils literal"><span class="pre">-1</span></tt> if
<em>sub</em> is not found.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The <a class="reference internal" href="#str.find" title="str.find"><tt class="xref py py-meth docutils literal"><span class="pre">find()</span></tt></a> method should be used only if you need to know the
position of <em>sub</em>.  To check if <em>sub</em> is a substring or not, use the
<a class="reference internal" href="../reference/expressions.html#in"><tt class="xref std std-keyword docutils literal"><span class="pre">in</span></tt></a> operator:</p>
<div class="last highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;Py&#39;</span> <span class="ow">in</span> <span class="s">&#39;Python&#39;</span>
<span class="go">True</span>
</pre></div>
</div>
</div>
</dd></dl>

<dl class="method">
<dt id="str.format">
<tt class="descclassname">str.</tt><tt class="descname">format</tt><big>(</big><em>*args</em>, <em>**kwargs</em><big>)</big><a class="headerlink" href="#str.format" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform a string formatting operation.  The string on which this method is
called can contain literal text or replacement fields delimited by braces
<tt class="docutils literal"><span class="pre">{}</span></tt>.  Each replacement field contains either the numeric index of a
positional argument, or the name of a keyword argument.  Returns a copy of
the string where each replacement field is replaced with the string value of
the corresponding argument.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="s">&quot;The sum of 1 + 2 is {0}&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mi">1</span><span class="o">+</span><span class="mi">2</span><span class="p">)</span>
<span class="go">&#39;The sum of 1 + 2 is 3&#39;</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="string.html#formatstrings"><em>Format String Syntax</em></a> for a description of the various formatting options
that can be specified in format strings.</p>
</dd></dl>

<dl class="method">
<dt id="str.format_map">
<tt class="descclassname">str.</tt><tt class="descname">format_map</tt><big>(</big><em>mapping</em><big>)</big><a class="headerlink" href="#str.format_map" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <tt class="docutils literal"><span class="pre">str.format(**mapping)</span></tt>, except that <tt class="docutils literal"><span class="pre">mapping</span></tt> is
used directly and not copied to a <a class="reference internal" href="#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> .  This is useful
if for example <tt class="docutils literal"><span class="pre">mapping</span></tt> is a dict subclass:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Default</span><span class="p">(</span><span class="nb">dict</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__missing__</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="gp">... </span>        <span class="k">return</span> <span class="n">key</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;{name} was born in {country}&#39;</span><span class="o">.</span><span class="n">format_map</span><span class="p">(</span><span class="n">Default</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&#39;Guido&#39;</span><span class="p">))</span>
<span class="go">&#39;Guido was born in country&#39;</span>
</pre></div>
</div>
<p class="versionadded">
<span class="versionmodified">New in version 3.2.</span> </p>
</dd></dl>

<dl class="method">
<dt id="str.index">
<tt class="descclassname">str.</tt><tt class="descname">index</tt><big>(</big><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.index" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#str.find" title="str.find"><tt class="xref py py-meth docutils literal"><span class="pre">find()</span></tt></a>, but raise <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> when the substring is not found.</p>
</dd></dl>

<dl class="method">
<dt id="str.isalnum">
<tt class="descclassname">str.</tt><tt class="descname">isalnum</tt><big>(</big><big>)</big><a class="headerlink" href="#str.isalnum" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if all characters in the string are alphanumeric and there is at
least one character, false otherwise.  A character <tt class="docutils literal"><span class="pre">c</span></tt> is alphanumeric if one
of the following returns <tt class="xref docutils literal"><span class="pre">True</span></tt>: <tt class="docutils literal"><span class="pre">c.isalpha()</span></tt>, <tt class="docutils literal"><span class="pre">c.isdecimal()</span></tt>,
<tt class="docutils literal"><span class="pre">c.isdigit()</span></tt>, or <tt class="docutils literal"><span class="pre">c.isnumeric()</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="str.isalpha">
<tt class="descclassname">str.</tt><tt class="descname">isalpha</tt><big>(</big><big>)</big><a class="headerlink" href="#str.isalpha" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if all characters in the string are alphabetic and there is at least
one character, false otherwise.  Alphabetic characters are those characters defined
in the Unicode character database as &#8220;Letter&#8221;, i.e., those with general category
property being one of &#8220;Lm&#8221;, &#8220;Lt&#8221;, &#8220;Lu&#8221;, &#8220;Ll&#8221;, or &#8220;Lo&#8221;.  Note that this is different
from the &#8220;Alphabetic&#8221; property defined in the Unicode Standard.</p>
</dd></dl>

<dl class="method">
<dt id="str.isdecimal">
<tt class="descclassname">str.</tt><tt class="descname">isdecimal</tt><big>(</big><big>)</big><a class="headerlink" href="#str.isdecimal" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if all characters in the string are decimal
characters and there is at least one character, false
otherwise. Decimal characters are those from general category &#8220;Nd&#8221;. This category
includes digit characters, and all characters
that can be used to form decimal-radix numbers, e.g. U+0660,
ARABIC-INDIC DIGIT ZERO.</p>
</dd></dl>

<dl class="method">
<dt id="str.isdigit">
<tt class="descclassname">str.</tt><tt class="descname">isdigit</tt><big>(</big><big>)</big><a class="headerlink" href="#str.isdigit" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if all characters in the string are digits and there is at least one
character, false otherwise.  Digits include decimal characters and digits that need
special handling, such as the compatibility superscript digits.  Formally, a digit
is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.</p>
</dd></dl>

<dl class="method">
<dt id="str.isidentifier">
<tt class="descclassname">str.</tt><tt class="descname">isidentifier</tt><big>(</big><big>)</big><a class="headerlink" href="#str.isidentifier" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the string is a valid identifier according to the language
definition, section <a class="reference internal" href="../reference/lexical_analysis.html#identifiers"><em>Identifiers and keywords</em></a>.</p>
</dd></dl>

<dl class="method">
<dt id="str.islower">
<tt class="descclassname">str.</tt><tt class="descname">islower</tt><big>(</big><big>)</big><a class="headerlink" href="#str.islower" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if all cased characters <a class="footnote-reference" href="#id13" id="id5">[4]</a> in the string are lowercase and
there is at least one cased character, false otherwise.</p>
</dd></dl>

<dl class="method">
<dt id="str.isnumeric">
<tt class="descclassname">str.</tt><tt class="descname">isnumeric</tt><big>(</big><big>)</big><a class="headerlink" href="#str.isnumeric" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if all characters in the string are numeric
characters, and there is at least one character, false
otherwise. Numeric characters include digit characters, and all characters
that have the Unicode numeric value property, e.g. U+2155,
VULGAR FRACTION ONE FIFTH.  Formally, numeric characters are those with the property
value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.</p>
</dd></dl>

<dl class="method">
<dt id="str.isprintable">
<tt class="descclassname">str.</tt><tt class="descname">isprintable</tt><big>(</big><big>)</big><a class="headerlink" href="#str.isprintable" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if all characters in the string are printable or the string is
empty, false otherwise.  Nonprintable characters are those characters defined
in the Unicode character database as &#8220;Other&#8221; or &#8220;Separator&#8221;, excepting the
ASCII space (0x20) which is considered printable.  (Note that printable
characters in this context are those which should not be escaped when
<a class="reference internal" href="functions.html#repr" title="repr"><tt class="xref py py-func docutils literal"><span class="pre">repr()</span></tt></a> is invoked on a string.  It has no bearing on the handling of
strings written to <a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><tt class="xref py py-data docutils literal"><span class="pre">sys.stdout</span></tt></a> or <a class="reference internal" href="sys.html#sys.stderr" title="sys.stderr"><tt class="xref py py-data docutils literal"><span class="pre">sys.stderr</span></tt></a>.)</p>
</dd></dl>

<dl class="method">
<dt id="str.isspace">
<tt class="descclassname">str.</tt><tt class="descname">isspace</tt><big>(</big><big>)</big><a class="headerlink" href="#str.isspace" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if there are only whitespace characters in the string and there is
at least one character, false otherwise.  Whitespace characters  are those
characters defined in the Unicode character database as &#8220;Other&#8221; or &#8220;Separator&#8221;
and those with bidirectional property being one of &#8220;WS&#8221;, &#8220;B&#8221;, or &#8220;S&#8221;.</p>
</dd></dl>

<dl class="method">
<dt id="str.istitle">
<tt class="descclassname">str.</tt><tt class="descname">istitle</tt><big>(</big><big>)</big><a class="headerlink" href="#str.istitle" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the string is a titlecased string and there is at least one
character, for example uppercase characters may only follow uncased characters
and lowercase characters only cased ones.  Return false otherwise.</p>
</dd></dl>

<dl class="method">
<dt id="str.isupper">
<tt class="descclassname">str.</tt><tt class="descname">isupper</tt><big>(</big><big>)</big><a class="headerlink" href="#str.isupper" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if all cased characters <a class="footnote-reference" href="#id13" id="id6">[4]</a> in the string are uppercase and
there is at least one cased character, false otherwise.</p>
</dd></dl>

<dl class="method">
<dt id="str.join">
<tt class="descclassname">str.</tt><tt class="descname">join</tt><big>(</big><em>iterable</em><big>)</big><a class="headerlink" href="#str.join" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string which is the concatenation of the strings in the
<a class="reference internal" href="../glossary.html#term-iterable"><em class="xref std std-term">iterable</em></a> <em>iterable</em>.  A <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> will be raised if there are
any non-string values in <em>iterable</em>, including <a class="reference internal" href="functions.html#bytes" title="bytes"><tt class="xref py py-class docutils literal"><span class="pre">bytes</span></tt></a> objects.  The
separator between elements is the string providing this method.</p>
</dd></dl>

<dl class="method">
<dt id="str.ljust">
<tt class="descclassname">str.</tt><tt class="descname">ljust</tt><big>(</big><em>width</em><span class="optional">[</span>, <em>fillchar</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.ljust" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the string left justified in a string of length <em>width</em>. Padding is done
using the specified <em>fillchar</em> (default is a space).  The original string is
returned if <em>width</em> is less than or equal to <tt class="docutils literal"><span class="pre">len(s)</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="str.lower">
<tt class="descclassname">str.</tt><tt class="descname">lower</tt><big>(</big><big>)</big><a class="headerlink" href="#str.lower" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with all the cased characters <a class="footnote-reference" href="#id13" id="id7">[4]</a> converted to
lowercase.</p>
<p>The lowercasing algorithm used is described in section 3.13 of the Unicode
Standard.</p>
</dd></dl>

<dl class="method">
<dt id="str.lstrip">
<tt class="descclassname">str.</tt><tt class="descname">lstrip</tt><big>(</big><span class="optional">[</span><em>chars</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.lstrip" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with leading characters removed.  The <em>chars</em>
argument is a string specifying the set of characters to be removed.  If omitted
or <tt class="xref docutils literal"><span class="pre">None</span></tt>, the <em>chars</em> argument defaults to removing whitespace.  The <em>chars</em>
argument is not a prefix; rather, all combinations of its values are stripped:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;   spacious   &#39;</span><span class="o">.</span><span class="n">lstrip</span><span class="p">()</span>
<span class="go">&#39;spacious   &#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;www.example.com&#39;</span><span class="o">.</span><span class="n">lstrip</span><span class="p">(</span><span class="s">&#39;cmowz.&#39;</span><span class="p">)</span>
<span class="go">&#39;example.com&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="staticmethod">
<dt id="str.maketrans">
<em class="property">static </em><tt class="descclassname">str.</tt><tt class="descname">maketrans</tt><big>(</big><em>x</em><span class="optional">[</span>, <em>y</em><span class="optional">[</span>, <em>z</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.maketrans" title="Permalink to this definition">¶</a></dt>
<dd><p>This static method returns a translation table usable for <a class="reference internal" href="#str.translate" title="str.translate"><tt class="xref py py-meth docutils literal"><span class="pre">str.translate()</span></tt></a>.</p>
<p>If there is only one argument, it must be a dictionary mapping Unicode
ordinals (integers) or characters (strings of length 1) to Unicode ordinals,
strings (of arbitrary lengths) or None.  Character keys will then be
converted to ordinals.</p>
<p>If there are two arguments, they must be strings of equal length, and in the
resulting dictionary, each character in x will be mapped to the character at
the same position in y.  If there is a third argument, it must be a string,
whose characters will be mapped to None in the result.</p>
</dd></dl>

<dl class="method">
<dt id="str.partition">
<tt class="descclassname">str.</tt><tt class="descname">partition</tt><big>(</big><em>sep</em><big>)</big><a class="headerlink" href="#str.partition" title="Permalink to this definition">¶</a></dt>
<dd><p>Split the string at the first occurrence of <em>sep</em>, and return a 3-tuple
containing the part before the separator, the separator itself, and the part
after the separator.  If the separator is not found, return a 3-tuple containing
the string itself, followed by two empty strings.</p>
</dd></dl>

<dl class="method">
<dt id="str.replace">
<tt class="descclassname">str.</tt><tt class="descname">replace</tt><big>(</big><em>old</em>, <em>new</em><span class="optional">[</span>, <em>count</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.replace" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with all occurrences of substring <em>old</em> replaced by
<em>new</em>.  If the optional argument <em>count</em> is given, only the first <em>count</em>
occurrences are replaced.</p>
</dd></dl>

<dl class="method">
<dt id="str.rfind">
<tt class="descclassname">str.</tt><tt class="descname">rfind</tt><big>(</big><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.rfind" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the highest index in the string where substring <em>sub</em> is found, such
that <em>sub</em> is contained within <tt class="docutils literal"><span class="pre">s[start:end]</span></tt>.  Optional arguments <em>start</em>
and <em>end</em> are interpreted as in slice notation.  Return <tt class="docutils literal"><span class="pre">-1</span></tt> on failure.</p>
</dd></dl>

<dl class="method">
<dt id="str.rindex">
<tt class="descclassname">str.</tt><tt class="descname">rindex</tt><big>(</big><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.rindex" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#str.rfind" title="str.rfind"><tt class="xref py py-meth docutils literal"><span class="pre">rfind()</span></tt></a> but raises <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> when the substring <em>sub</em> is not
found.</p>
</dd></dl>

<dl class="method">
<dt id="str.rjust">
<tt class="descclassname">str.</tt><tt class="descname">rjust</tt><big>(</big><em>width</em><span class="optional">[</span>, <em>fillchar</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.rjust" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the string right justified in a string of length <em>width</em>. Padding is done
using the specified <em>fillchar</em> (default is a space). The original string is
returned if <em>width</em> is less than or equal to <tt class="docutils literal"><span class="pre">len(s)</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="str.rpartition">
<tt class="descclassname">str.</tt><tt class="descname">rpartition</tt><big>(</big><em>sep</em><big>)</big><a class="headerlink" href="#str.rpartition" title="Permalink to this definition">¶</a></dt>
<dd><p>Split the string at the last occurrence of <em>sep</em>, and return a 3-tuple
containing the part before the separator, the separator itself, and the part
after the separator.  If the separator is not found, return a 3-tuple containing
two empty strings, followed by the string itself.</p>
</dd></dl>

<dl class="method">
<dt id="str.rsplit">
<tt class="descclassname">str.</tt><tt class="descname">rsplit</tt><big>(</big><em>sep=None</em>, <em>maxsplit=-1</em><big>)</big><a class="headerlink" href="#str.rsplit" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the words in the string, using <em>sep</em> as the delimiter string.
If <em>maxsplit</em> is given, at most <em>maxsplit</em> splits are done, the <em>rightmost</em>
ones.  If <em>sep</em> is not specified or <tt class="xref docutils literal"><span class="pre">None</span></tt>, any whitespace string is a
separator.  Except for splitting from the right, <a class="reference internal" href="#str.rsplit" title="str.rsplit"><tt class="xref py py-meth docutils literal"><span class="pre">rsplit()</span></tt></a> behaves like
<a class="reference internal" href="#str.split" title="str.split"><tt class="xref py py-meth docutils literal"><span class="pre">split()</span></tt></a> which is described in detail below.</p>
</dd></dl>

<dl class="method">
<dt id="str.rstrip">
<tt class="descclassname">str.</tt><tt class="descname">rstrip</tt><big>(</big><span class="optional">[</span><em>chars</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.rstrip" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with trailing characters removed.  The <em>chars</em>
argument is a string specifying the set of characters to be removed.  If omitted
or <tt class="xref docutils literal"><span class="pre">None</span></tt>, the <em>chars</em> argument defaults to removing whitespace.  The <em>chars</em>
argument is not a suffix; rather, all combinations of its values are stripped:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;   spacious   &#39;</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()</span>
<span class="go">&#39;   spacious&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;mississippi&#39;</span><span class="o">.</span><span class="n">rstrip</span><span class="p">(</span><span class="s">&#39;ipz&#39;</span><span class="p">)</span>
<span class="go">&#39;mississ&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="str.split">
<tt class="descclassname">str.</tt><tt class="descname">split</tt><big>(</big><em>sep=None</em>, <em>maxsplit=-1</em><big>)</big><a class="headerlink" href="#str.split" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the words in the string, using <em>sep</em> as the delimiter
string.  If <em>maxsplit</em> is given, at most <em>maxsplit</em> splits are done (thus,
the list will have at most <tt class="docutils literal"><span class="pre">maxsplit+1</span></tt> elements).  If <em>maxsplit</em> is not
specified or <tt class="docutils literal"><span class="pre">-1</span></tt>, then there is no limit on the number of splits
(all possible splits are made).</p>
<p>If <em>sep</em> is given, consecutive delimiters are not grouped together and are
deemed to delimit empty strings (for example, <tt class="docutils literal"><span class="pre">'1,,2'.split(',')</span></tt> returns
<tt class="docutils literal"><span class="pre">['1',</span> <span class="pre">'',</span> <span class="pre">'2']</span></tt>).  The <em>sep</em> argument may consist of multiple characters
(for example, <tt class="docutils literal"><span class="pre">'1&lt;&gt;2&lt;&gt;3'.split('&lt;&gt;')</span></tt> returns <tt class="docutils literal"><span class="pre">['1',</span> <span class="pre">'2',</span> <span class="pre">'3']</span></tt>).
Splitting an empty string with a specified separator returns <tt class="docutils literal"><span class="pre">['']</span></tt>.</p>
<p>If <em>sep</em> is not specified or is <tt class="xref docutils literal"><span class="pre">None</span></tt>, a different splitting algorithm is
applied: runs of consecutive whitespace are regarded as a single separator,
and the result will contain no empty strings at the start or end if the
string has leading or trailing whitespace.  Consequently, splitting an empty
string or a string consisting of just whitespace with a <tt class="xref docutils literal"><span class="pre">None</span></tt> separator
returns <tt class="docutils literal"><span class="pre">[]</span></tt>.</p>
<p>For example, <tt class="docutils literal"><span class="pre">'</span> <span class="pre">1</span>&nbsp; <span class="pre">2</span>&nbsp;&nbsp; <span class="pre">3</span>&nbsp; <span class="pre">'.split()</span></tt> returns <tt class="docutils literal"><span class="pre">['1',</span> <span class="pre">'2',</span> <span class="pre">'3']</span></tt>, and
<tt class="docutils literal"><span class="pre">'</span>&nbsp; <span class="pre">1</span>&nbsp; <span class="pre">2</span>&nbsp;&nbsp; <span class="pre">3</span>&nbsp; <span class="pre">'.split(None,</span> <span class="pre">1)</span></tt> returns <tt class="docutils literal"><span class="pre">['1',</span> <span class="pre">'2</span>&nbsp;&nbsp; <span class="pre">3</span>&nbsp; <span class="pre">']</span></tt>.</p>
</dd></dl>

<span class="target" id="index-29"></span><dl class="method">
<dt id="str.splitlines">
<tt class="descclassname">str.</tt><tt class="descname">splitlines</tt><big>(</big><span class="optional">[</span><em>keepends</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.splitlines" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the lines in the string, breaking at line boundaries.
This method uses the <a class="reference internal" href="../glossary.html#term-universal-newlines"><em class="xref std std-term">universal newlines</em></a> approach to splitting lines.
Line breaks are not included in the resulting list unless <em>keepends</em> is
given and true.</p>
<p>For example, <tt class="docutils literal"><span class="pre">'ab</span> <span class="pre">c\n\nde</span> <span class="pre">fg\rkl\r\n'.splitlines()</span></tt> returns
<tt class="docutils literal"><span class="pre">['ab</span> <span class="pre">c',</span> <span class="pre">'',</span> <span class="pre">'de</span> <span class="pre">fg',</span> <span class="pre">'kl']</span></tt>, while the same call with <tt class="docutils literal"><span class="pre">splitlines(True)</span></tt>
returns <tt class="docutils literal"><span class="pre">['ab</span> <span class="pre">c\n',</span> <span class="pre">'\n',</span> <span class="pre">'de</span> <span class="pre">fg\r',</span> <span class="pre">'kl\r\n']</span></tt>.</p>
<p>Unlike <a class="reference internal" href="#str.split" title="str.split"><tt class="xref py py-meth docutils literal"><span class="pre">split()</span></tt></a> when a delimiter string <em>sep</em> is given, this
method returns an empty list for the empty string, and a terminal line
break does not result in an extra line.</p>
</dd></dl>

<dl class="method">
<dt id="str.startswith">
<tt class="descclassname">str.</tt><tt class="descname">startswith</tt><big>(</big><em>prefix</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.startswith" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <tt class="xref docutils literal"><span class="pre">True</span></tt> if string starts with the <em>prefix</em>, otherwise return <tt class="xref docutils literal"><span class="pre">False</span></tt>.
<em>prefix</em> can also be a tuple of prefixes to look for.  With optional <em>start</em>,
test string beginning at that position.  With optional <em>end</em>, stop comparing
string at that position.</p>
</dd></dl>

<dl class="method">
<dt id="str.strip">
<tt class="descclassname">str.</tt><tt class="descname">strip</tt><big>(</big><span class="optional">[</span><em>chars</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#str.strip" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with the leading and trailing characters removed.
The <em>chars</em> argument is a string specifying the set of characters to be removed.
If omitted or <tt class="xref docutils literal"><span class="pre">None</span></tt>, the <em>chars</em> argument defaults to removing whitespace.
The <em>chars</em> argument is not a prefix or suffix; rather, all combinations of its
values are stripped:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;   spacious   &#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>
<span class="go">&#39;spacious&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;www.example.com&#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="s">&#39;cmowz.&#39;</span><span class="p">)</span>
<span class="go">&#39;example&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="str.swapcase">
<tt class="descclassname">str.</tt><tt class="descname">swapcase</tt><big>(</big><big>)</big><a class="headerlink" href="#str.swapcase" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with uppercase characters converted to lowercase and
vice versa. Note that it is not necessarily true that
<tt class="docutils literal"><span class="pre">s.swapcase().swapcase()</span> <span class="pre">==</span> <span class="pre">s</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="str.title">
<tt class="descclassname">str.</tt><tt class="descname">title</tt><big>(</big><big>)</big><a class="headerlink" href="#str.title" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a titlecased version of the string where words start with an uppercase
character and the remaining characters are lowercase.</p>
<p>The algorithm uses a simple language-independent definition of a word as
groups of consecutive letters.  The definition works in many contexts but
it means that apostrophes in contractions and possessives form word
boundaries, which may not be the desired result:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="s">&quot;they&#39;re bill&#39;s friends from the UK&quot;</span><span class="o">.</span><span class="n">title</span><span class="p">()</span>
<span class="go">&quot;They&#39;Re Bill&#39;S Friends From The Uk&quot;</span>
</pre></div>
</div>
<p>A workaround for apostrophes can be constructed using regular expressions:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">titlecase</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
<span class="go">        return re.sub(r&quot;[A-Za-z]+(&#39;[A-Za-z]+)?&quot;,</span>
<span class="go">                      lambda mo: mo.group(0)[0].upper() +</span>
<span class="go">                                 mo.group(0)[1:].lower(),</span>
<span class="go">                      s)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">titlecase</span><span class="p">(</span><span class="s">&quot;they&#39;re bill&#39;s friends.&quot;</span><span class="p">)</span>
<span class="go">&quot;They&#39;re Bill&#39;s Friends.&quot;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="str.translate">
<tt class="descclassname">str.</tt><tt class="descname">translate</tt><big>(</big><em>map</em><big>)</big><a class="headerlink" href="#str.translate" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the <em>s</em> where all characters have been mapped through the
<em>map</em> which must be a dictionary of Unicode ordinals (integers) to Unicode
ordinals, strings or <tt class="xref docutils literal"><span class="pre">None</span></tt>.  Unmapped characters are left untouched.
Characters mapped to <tt class="xref docutils literal"><span class="pre">None</span></tt> are deleted.</p>
<p>You can use <a class="reference internal" href="#str.maketrans" title="str.maketrans"><tt class="xref py py-meth docutils literal"><span class="pre">str.maketrans()</span></tt></a> to create a translation map from
character-to-character mappings in different formats.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">An even more flexible approach is to create a custom character mapping
codec using the <a class="reference internal" href="codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><tt class="xref py py-mod docutils literal"><span class="pre">codecs</span></tt></a> module (see <tt class="xref py py-mod docutils literal"><span class="pre">encodings.cp1251</span></tt> for an
example).</p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.upper">
<tt class="descclassname">str.</tt><tt class="descname">upper</tt><big>(</big><big>)</big><a class="headerlink" href="#str.upper" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with all the cased characters <a class="footnote-reference" href="#id13" id="id8">[4]</a> converted to
uppercase.  Note that <tt class="docutils literal"><span class="pre">str.upper().isupper()</span></tt> might be <tt class="xref docutils literal"><span class="pre">False</span></tt> if <tt class="docutils literal"><span class="pre">s</span></tt>
contains uncased characters or if the Unicode category of the resulting
character(s) is not &#8220;Lu&#8221; (Letter, uppercase), but e.g. &#8220;Lt&#8221; (Letter,
titlecase).</p>
<p>The uppercasing algorithm used is described in section 3.13 of the Unicode
Standard.</p>
</dd></dl>

<dl class="method">
<dt id="str.zfill">
<tt class="descclassname">str.</tt><tt class="descname">zfill</tt><big>(</big><em>width</em><big>)</big><a class="headerlink" href="#str.zfill" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the numeric string left filled with zeros in a string of length
<em>width</em>.  A sign prefix is handled correctly.  The original string is
returned if <em>width</em> is less than or equal to <tt class="docutils literal"><span class="pre">len(s)</span></tt>.</p>
</dd></dl>

</div>
<div class="section" id="printf-style-string-formatting">
<span id="old-string-formatting"></span><h3>4.7.2. <tt class="docutils literal"><span class="pre">printf</span></tt>-style String Formatting<a class="headerlink" href="#printf-style-string-formatting" title="Permalink to this headline">¶</a></h3>
<div class="admonition note" id="index-30">
<p class="first admonition-title">Note</p>
<p class="last">The formatting operations described here exhibit a variety of quirks that
lead to a number of common errors (such as failing to display tuples and
dictionaries correctly).  Using the newer <a class="reference internal" href="#str.format" title="str.format"><tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt></a> interface
helps avoid these errors, and also provides a generally more powerful,
flexible and extensible approach to formatting text.</p>
</div>
<p>String objects have one unique built-in operation: the <tt class="docutils literal"><span class="pre">%</span></tt> operator (modulo).
This is also known as the string <em>formatting</em> or <em>interpolation</em> operator.
Given <tt class="docutils literal"><span class="pre">format</span> <span class="pre">%</span> <span class="pre">values</span></tt> (where <em>format</em> is a string), <tt class="docutils literal"><span class="pre">%</span></tt> conversion
specifications in <em>format</em> are replaced with zero or more elements of <em>values</em>.
The effect is similar to using the <tt class="xref c c-func docutils literal"><span class="pre">sprintf()</span></tt> in the C language.</p>
<p>If <em>format</em> requires a single argument, <em>values</em> may be a single non-tuple
object. <a class="footnote-reference" href="#id14" id="id9">[5]</a>  Otherwise, <em>values</em> must be a tuple with exactly the number of
items specified by the format string, or a single mapping object (for example, a
dictionary).</p>
<p>A conversion specifier contains two or more characters and has the following
components, which must occur in this order:</p>
<ol class="arabic simple">
<li>The <tt class="docutils literal"><span class="pre">'%'</span></tt> character, which marks the start of the specifier.</li>
<li>Mapping key (optional), consisting of a parenthesised sequence of characters
(for example, <tt class="docutils literal"><span class="pre">(somename)</span></tt>).</li>
<li>Conversion flags (optional), which affect the result of some conversion
types.</li>
<li>Minimum field width (optional).  If specified as an <tt class="docutils literal"><span class="pre">'*'</span></tt> (asterisk), the
actual width is read from the next element of the tuple in <em>values</em>, and the
object to convert comes after the minimum field width and optional precision.</li>
<li>Precision (optional), given as a <tt class="docutils literal"><span class="pre">'.'</span></tt> (dot) followed by the precision.  If
specified as <tt class="docutils literal"><span class="pre">'*'</span></tt> (an asterisk), the actual precision is read from the next
element of the tuple in <em>values</em>, and the value to convert comes after the
precision.</li>
<li>Length modifier (optional).</li>
<li>Conversion type.</li>
</ol>
<p>When the right argument is a dictionary (or other mapping type), then the
formats in the string <em>must</em> include a parenthesised mapping key into that
dictionary inserted immediately after the <tt class="docutils literal"><span class="pre">'%'</span></tt> character. The mapping key
selects the value to be formatted from the mapping.  For example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s">&#39;%(language)s has %(number)03d quote types.&#39;</span> <span class="o">%</span>
<span class="gp">... </span>      <span class="p">{</span><span class="s">&#39;language&#39;</span><span class="p">:</span> <span class="s">&quot;Python&quot;</span><span class="p">,</span> <span class="s">&quot;number&quot;</span><span class="p">:</span> <span class="mi">2</span><span class="p">})</span>
<span class="go">Python has 002 quote types.</span>
</pre></div>
</div>
<p>In this case no <tt class="docutils literal"><span class="pre">*</span></tt> specifiers may occur in a format (since they require a
sequential parameter list).</p>
<p>The conversion flag characters are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="12%" />
<col width="88%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Flag</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><tt class="docutils literal"><span class="pre">'#'</span></tt></td>
<td>The value conversion will use the &#8220;alternate form&#8221; (where defined
below).</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'0'</span></tt></td>
<td>The conversion will be zero padded for numeric values.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'-'</span></tt></td>
<td>The converted value is left adjusted (overrides the <tt class="docutils literal"><span class="pre">'0'</span></tt>
conversion if both are given).</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'</span> <span class="pre">'</span></tt></td>
<td>(a space) A blank should be left before a positive number (or empty
string) produced by a signed conversion.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'+'</span></tt></td>
<td>A sign character (<tt class="docutils literal"><span class="pre">'+'</span></tt> or <tt class="docutils literal"><span class="pre">'-'</span></tt>) will precede the conversion
(overrides a &#8220;space&#8221; flag).</td>
</tr>
</tbody>
</table>
<p>A length modifier (<tt class="docutils literal"><span class="pre">h</span></tt>, <tt class="docutils literal"><span class="pre">l</span></tt>, or <tt class="docutils literal"><span class="pre">L</span></tt>) may be present, but is ignored as it
is not necessary for Python &#8211; so e.g. <tt class="docutils literal"><span class="pre">%ld</span></tt> is identical to <tt class="docutils literal"><span class="pre">%d</span></tt>.</p>
<p>The conversion types are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="17%" />
<col width="74%" />
<col width="10%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Conversion</th>
<th class="head">Meaning</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><tt class="docutils literal"><span class="pre">'d'</span></tt></td>
<td>Signed integer decimal.</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'i'</span></tt></td>
<td>Signed integer decimal.</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'o'</span></tt></td>
<td>Signed octal value.</td>
<td>(1)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'u'</span></tt></td>
<td>Obsolete type &#8211; it is identical to <tt class="docutils literal"><span class="pre">'d'</span></tt>.</td>
<td>(7)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'x'</span></tt></td>
<td>Signed hexadecimal (lowercase).</td>
<td>(2)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'X'</span></tt></td>
<td>Signed hexadecimal (uppercase).</td>
<td>(2)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'e'</span></tt></td>
<td>Floating point exponential format (lowercase).</td>
<td>(3)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'E'</span></tt></td>
<td>Floating point exponential format (uppercase).</td>
<td>(3)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'f'</span></tt></td>
<td>Floating point decimal format.</td>
<td>(3)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'F'</span></tt></td>
<td>Floating point decimal format.</td>
<td>(3)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'g'</span></tt></td>
<td>Floating point format. Uses lowercase exponential
format if exponent is less than -4 or not less than
precision, decimal format otherwise.</td>
<td>(4)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'G'</span></tt></td>
<td>Floating point format. Uses uppercase exponential
format if exponent is less than -4 or not less than
precision, decimal format otherwise.</td>
<td>(4)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'c'</span></tt></td>
<td>Single character (accepts integer or single
character string).</td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'r'</span></tt></td>
<td>String (converts any Python object using
<a class="reference internal" href="functions.html#repr" title="repr"><tt class="xref py py-func docutils literal"><span class="pre">repr()</span></tt></a>).</td>
<td>(5)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'s'</span></tt></td>
<td>String (converts any Python object using
<a class="reference internal" href="functions.html#str" title="str"><tt class="xref py py-func docutils literal"><span class="pre">str()</span></tt></a>).</td>
<td>(5)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'a'</span></tt></td>
<td>String (converts any Python object using
<a class="reference internal" href="functions.html#ascii" title="ascii"><tt class="xref py py-func docutils literal"><span class="pre">ascii()</span></tt></a>).</td>
<td>(5)</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">'%'</span></tt></td>
<td>No argument is converted, results in a <tt class="docutils literal"><span class="pre">'%'</span></tt>
character in the result.</td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic">
<li><p class="first">The alternate form causes a leading zero (<tt class="docutils literal"><span class="pre">'0'</span></tt>) to be inserted between
left-hand padding and the formatting of the number if the leading character
of the result is not already a zero.</p>
</li>
<li><p class="first">The alternate form causes a leading <tt class="docutils literal"><span class="pre">'0x'</span></tt> or <tt class="docutils literal"><span class="pre">'0X'</span></tt> (depending on whether
the <tt class="docutils literal"><span class="pre">'x'</span></tt> or <tt class="docutils literal"><span class="pre">'X'</span></tt> format was used) to be inserted between left-hand padding
and the formatting of the number if the leading character of the result is not
already a zero.</p>
</li>
<li><p class="first">The alternate form causes the result to always contain a decimal point, even if
no digits follow it.</p>
<p>The precision determines the number of digits after the decimal point and
defaults to 6.</p>
</li>
<li><p class="first">The alternate form causes the result to always contain a decimal point, and
trailing zeroes are not removed as they would otherwise be.</p>
<p>The precision determines the number of significant digits before and after the
decimal point and defaults to 6.</p>
</li>
<li><p class="first">If precision is <tt class="docutils literal"><span class="pre">N</span></tt>, the output is truncated to <tt class="docutils literal"><span class="pre">N</span></tt> characters.</p>
</li>
</ol>
<ol class="arabic simple" start="7">
<li>See <span class="target" id="index-31"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0237"><strong>PEP 237</strong></a>.</li>
</ol>
<p>Since Python strings have an explicit length, <tt class="docutils literal"><span class="pre">%s</span></tt> conversions do not assume
that <tt class="docutils literal"><span class="pre">'\0'</span></tt> is the end of the string.</p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 3.1:</span> <tt class="docutils literal"><span class="pre">%f</span></tt> conversions for numbers whose absolute value is over 1e50 are no
longer replaced by <tt class="docutils literal"><span class="pre">%g</span></tt> conversions.</p>
</div>
</div>
<div class="section" id="binary-sequence-types-bytes-bytearray-memoryview">
<span id="binaryseq"></span><h2>4.8. Binary Sequence Types &#8212; <a class="reference internal" href="functions.html#bytes" title="bytes"><tt class="xref py py-class docutils literal"><span class="pre">bytes</span></tt></a>, <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a>, <a class="reference internal" href="#memoryview" title="memoryview"><tt class="xref py py-class docutils literal"><span class="pre">memoryview</span></tt></a><a class="headerlink" href="#binary-sequence-types-bytes-bytearray-memoryview" title="Permalink to this headline">¶</a></h2>
<p id="index-32">The core built-in types for manipulating binary data are <a class="reference internal" href="functions.html#bytes" title="bytes"><tt class="xref py py-class docutils literal"><span class="pre">bytes</span></tt></a> and
<a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a>. They are supported by <a class="reference internal" href="#memoryview" title="memoryview"><tt class="xref py py-class docutils literal"><span class="pre">memoryview</span></tt></a> which uses
the buffer protocol to access the memory of other binary objects without
needing to make a copy.</p>
<p>The <a class="reference internal" href="array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><tt class="xref py py-mod docutils literal"><span class="pre">array</span></tt></a> module supports efficient storage of basic data types like
32-bit integers and IEEE754 double-precision floating values.</p>
<div class="section" id="bytes">
<span id="typebytes"></span><h3>4.8.1. Bytes<a class="headerlink" href="#bytes" title="Permalink to this headline">¶</a></h3>
<p id="index-33">Bytes objects are immutable sequences of single bytes. Since many major
binary protocols are based on the ASCII text encoding, bytes objects offer
several methods that are only valid when working with ASCII compatible
data and are closely related to string objects in a variety of other ways.</p>
<p>Firstly, the syntax for bytes literals is largely the same as that for string
literals, except that a <tt class="docutils literal"><span class="pre">b</span></tt> prefix is added:</p>
<ul class="simple">
<li>Single quotes: <tt class="docutils literal"><span class="pre">b'still</span> <span class="pre">allows</span> <span class="pre">embedded</span> <span class="pre">&quot;double&quot;</span> <span class="pre">quotes'</span></tt></li>
<li>Double quotes: <tt class="docutils literal"><span class="pre">b&quot;still</span> <span class="pre">allows</span> <span class="pre">embedded</span> <span class="pre">'single'</span> <span class="pre">quotes&quot;</span></tt>.</li>
<li>Triple quoted: <tt class="docutils literal"><span class="pre">b'''3</span> <span class="pre">single</span> <span class="pre">quotes'''</span></tt>, <tt class="docutils literal"><span class="pre">b&quot;&quot;&quot;3</span> <span class="pre">double</span> <span class="pre">quotes&quot;&quot;&quot;</span></tt></li>
</ul>
<p>Only ASCII characters are permitted in bytes literals (regardless of the
declared source code encoding). Any binary values over 127 must be entered
into bytes literals using the appropriate escape sequence.</p>
<p>As with string literals, bytes literals may also use a <tt class="docutils literal"><span class="pre">r</span></tt> prefix to disable
processing of escape sequences. See <a class="reference internal" href="../reference/lexical_analysis.html#strings"><em>String and Bytes literals</em></a> for more about the various
forms of bytes literal, including supported escape sequences.</p>
<p>While bytes literals and representations are based on ASCII text, bytes
objects actually behave like immutable sequences of integers, with each
value in the sequence restricted such that <tt class="docutils literal"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">256</span></tt> (attempts to
violate this restriction will trigger <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a>. This is done
deliberately to emphasise that while many binary formats include ASCII based
elements and can be usefully manipulated with some text-oriented algorithms,
this is not generally the case for arbitrary binary data (blindly applying
text processing algorithms to binary data formats that are not ASCII
compatible will usually lead to data corruption).</p>
<p>In addition to the literal forms, bytes objects can be created in a number of
other ways:</p>
<ul class="simple">
<li>A zero-filled bytes object of a specified length: <tt class="docutils literal"><span class="pre">bytes(10)</span></tt></li>
<li>From an iterable of integers: <tt class="docutils literal"><span class="pre">bytes(range(20))</span></tt></li>
<li>Copying existing binary data via the buffer protocol:  <tt class="docutils literal"><span class="pre">bytes(obj)</span></tt></li>
</ul>
<p>Also see the <a class="reference internal" href="functions.html#func-bytes"><em>bytes</em></a> built-in.</p>
<p>Since bytes objects are sequences of integers, for a bytes object <em>b</em>,
<tt class="docutils literal"><span class="pre">b[0]</span></tt> will be an integer, while <tt class="docutils literal"><span class="pre">b[0:1]</span></tt> will be a bytes object of
length 1.  (This contrasts with text strings, where both indexing and
slicing will produce a string of length 1)</p>
<p>The representation of bytes objects uses the literal format (<tt class="docutils literal"><span class="pre">b'...'</span></tt>)
since it is often more useful than e.g. <tt class="docutils literal"><span class="pre">bytes([46,</span> <span class="pre">46,</span> <span class="pre">46])</span></tt>.  You can
always convert a bytes object into a list of integers using <tt class="docutils literal"><span class="pre">list(b)</span></tt>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">For Python 2.x users: In the Python 2.x series, a variety of implicit
conversions between 8-bit strings (the closest thing 2.x offers to a
built-in binary data type) and Unicode strings were permitted. This was a
backwards compatibility workaround to account for the fact that Python
originally only supported 8-bit text, and Unicode text was a later
addition. In Python 3.x, those implicit conversions are gone - conversions
between 8-bit binary data and Unicode text must be explicit, and bytes and
string objects will always compare unequal.</p>
</div>
</div>
<div class="section" id="bytearray-objects">
<span id="typebytearray"></span><h3>4.8.2. Bytearray Objects<a class="headerlink" href="#bytearray-objects" title="Permalink to this headline">¶</a></h3>
<p id="index-34"><a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a> objects are a mutable counterpart to <a class="reference internal" href="functions.html#bytes" title="bytes"><tt class="xref py py-class docutils literal"><span class="pre">bytes</span></tt></a>
objects. There is no dedicated literal syntax for bytearray objects, instead
they are always created by calling the constructor:</p>
<ul class="simple">
<li>Creating an empty instance: <tt class="docutils literal"><span class="pre">bytearray()</span></tt></li>
<li>Creating a zero-filled instance with a given length: <tt class="docutils literal"><span class="pre">bytearray(10)</span></tt></li>
<li>From an iterable of integers: <tt class="docutils literal"><span class="pre">bytearray(range(20))</span></tt></li>
<li>Copying existing binary data via the buffer protocol:  <tt class="docutils literal"><span class="pre">bytearray(b'Hi!)</span></tt></li>
</ul>
<p>As bytearray objects are mutable, they support the
<a class="reference internal" href="#typesseq-mutable"><em>mutable</em></a> sequence operations in addition to the
common bytes and bytearray operations described in <a class="reference internal" href="#bytes-methods"><em>Bytes and Bytearray Operations</em></a>.</p>
<p>Also see the <a class="reference internal" href="functions.html#func-bytearray"><em>bytearray</em></a> built-in.</p>
</div>
<div class="section" id="bytes-and-bytearray-operations">
<span id="bytes-methods"></span><h3>4.8.3. Bytes and Bytearray Operations<a class="headerlink" href="#bytes-and-bytearray-operations" title="Permalink to this headline">¶</a></h3>
<p id="index-35">Both bytes and bytearray objects support the <a class="reference internal" href="#typesseq-common"><em>common</em></a>
sequence operations. They interoperate not just with operands of the same
type, but with any object that supports the
<a class="reference internal" href="../c-api/buffer.html#bufferobjects"><em>buffer protocol</em></a>. Due to this flexibility, they can be
freely mixed in operations without causing errors. However, the return type
of the result may depend on the order of operands.</p>
<p>Due to the common use of ASCII text as the basis for binary protocols, bytes
and bytearray objects provide almost all methods found on text strings, with
the exceptions of:</p>
<ul class="simple">
<li><a class="reference internal" href="#str.encode" title="str.encode"><tt class="xref py py-meth docutils literal"><span class="pre">str.encode()</span></tt></a> (which converts text strings to bytes objects)</li>
<li><a class="reference internal" href="#str.format" title="str.format"><tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt></a> and <a class="reference internal" href="#str.format_map" title="str.format_map"><tt class="xref py py-meth docutils literal"><span class="pre">str.format_map()</span></tt></a> (which are used to format
text for display to users)</li>
<li><a class="reference internal" href="#str.isidentifier" title="str.isidentifier"><tt class="xref py py-meth docutils literal"><span class="pre">str.isidentifier()</span></tt></a>, <a class="reference internal" href="#str.isnumeric" title="str.isnumeric"><tt class="xref py py-meth docutils literal"><span class="pre">str.isnumeric()</span></tt></a>, <a class="reference internal" href="#str.isdecimal" title="str.isdecimal"><tt class="xref py py-meth docutils literal"><span class="pre">str.isdecimal()</span></tt></a>,
<a class="reference internal" href="#str.isprintable" title="str.isprintable"><tt class="xref py py-meth docutils literal"><span class="pre">str.isprintable()</span></tt></a> (which are used to check various properties of
text strings which are not typically applicable to binary protocols).</li>
</ul>
<p>All other string methods are supported, although sometimes with slight
differences in functionality and semantics (as described below).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The methods on bytes and bytearray objects don&#8217;t accept strings as their
arguments, just as the methods on strings don&#8217;t accept bytes as their
arguments.  For example, you have to write:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">a</span> <span class="o">=</span> <span class="s">&quot;abc&quot;</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">a</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s">&quot;a&quot;</span><span class="p">,</span> <span class="s">&quot;f&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>and:</p>
<div class="last highlight-python3"><div class="highlight"><pre><span class="n">a</span> <span class="o">=</span> <span class="n">b</span><span class="s">&quot;abc&quot;</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">a</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;a&quot;</span><span class="p">,</span> <span class="n">b</span><span class="s">&quot;f&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<p>Whenever a bytes or bytearray method needs to interpret the bytes as
characters (e.g. the <tt class="xref py py-meth docutils literal"><span class="pre">is...()</span></tt> methods, <tt class="xref py py-meth docutils literal"><span class="pre">split()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">strip()</span></tt>),
the ASCII character set is assumed (text strings use Unicode semantics).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Using these ASCII based methods to manipulate binary data that is not
stored in an ASCII based format may lead to data corruption.</p>
</div>
<p>The search operations (<a class="reference internal" href="../reference/expressions.html#in"><tt class="xref std std-keyword docutils literal"><span class="pre">in</span></tt></a>, <tt class="xref py py-meth docutils literal"><span class="pre">count()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">find()</span></tt>,
<tt class="xref py py-meth docutils literal"><span class="pre">index()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">rfind()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">rindex()</span></tt>) all accept both integers
in the range 0 to 255 (inclusive) as well as bytes and byte array sequences.</p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 3.3:</span> All of the search methods also accept an integer in the range 0 to 255
(inclusive) as their first argument.</p>
<p>Each bytes and bytearray instance provides a <tt class="xref py py-meth docutils literal"><span class="pre">decode()</span></tt> convenience
method that is the inverse of <a class="reference internal" href="#str.encode" title="str.encode"><tt class="xref py py-meth docutils literal"><span class="pre">str.encode()</span></tt></a>:</p>
<dl class="method">
<dt id="bytes.decode">
<tt class="descclassname">bytes.</tt><tt class="descname">decode</tt><big>(</big><em>encoding=&quot;utf-8&quot;</em>, <em>errors=&quot;strict&quot;</em><big>)</big><a class="headerlink" href="#bytes.decode" title="Permalink to this definition">¶</a></dt>
<dt id="bytearray.decode">
<tt class="descclassname">bytearray.</tt><tt class="descname">decode</tt><big>(</big><em>encoding=&quot;utf-8&quot;</em>, <em>errors=&quot;strict&quot;</em><big>)</big><a class="headerlink" href="#bytearray.decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string decoded from the given bytes.  Default encoding is
<tt class="docutils literal"><span class="pre">'utf-8'</span></tt>. <em>errors</em> may be given to set a different
error handling scheme.  The default for <em>errors</em> is <tt class="docutils literal"><span class="pre">'strict'</span></tt>, meaning
that encoding errors raise a <a class="reference internal" href="exceptions.html#UnicodeError" title="UnicodeError"><tt class="xref py py-exc docutils literal"><span class="pre">UnicodeError</span></tt></a>.  Other possible values are
<tt class="docutils literal"><span class="pre">'ignore'</span></tt>, <tt class="docutils literal"><span class="pre">'replace'</span></tt> and any other name registered via
<a class="reference internal" href="codecs.html#codecs.register_error" title="codecs.register_error"><tt class="xref py py-func docutils literal"><span class="pre">codecs.register_error()</span></tt></a>, see section <a class="reference internal" href="codecs.html#codec-base-classes"><em>Codec Base Classes</em></a>. For a
list of possible encodings, see section <a class="reference internal" href="codecs.html#standard-encodings"><em>Standard Encodings</em></a>.</p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 3.1:</span> Added support for keyword arguments.</p>
</dd></dl>

<p>Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal
numbers are a commonly used format for describing binary data. Accordingly,
the bytes and bytearray types have an additional class method to read data in
that format:</p>
<dl class="classmethod">
<dt id="bytes.fromhex">
<em class="property">classmethod </em><tt class="descclassname">bytes.</tt><tt class="descname">fromhex</tt><big>(</big><em>string</em><big>)</big><a class="headerlink" href="#bytes.fromhex" title="Permalink to this definition">¶</a></dt>
<dt id="bytearray.fromhex">
<em class="property">classmethod </em><tt class="descclassname">bytearray.</tt><tt class="descname">fromhex</tt><big>(</big><em>string</em><big>)</big><a class="headerlink" href="#bytearray.fromhex" title="Permalink to this definition">¶</a></dt>
<dd><p>This <a class="reference internal" href="functions.html#bytes" title="bytes"><tt class="xref py py-class docutils literal"><span class="pre">bytes</span></tt></a> class method returns a bytes or bytearray object,
decoding the given string object.  The string must contain two hexadecimal
digits per byte, spaces are ignored.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">bytes</span><span class="o">.</span><span class="n">fromhex</span><span class="p">(</span><span class="s">&#39;2Ef0 F1f2  &#39;</span><span class="p">)</span>
<span class="go">b&#39;.\xf0\xf1\xf2&#39;</span>
</pre></div>
</div>
</dd></dl>

<p>The maketrans and translate methods differ in semantics from the versions
available on strings:</p>
<dl class="method">
<dt id="bytes.translate">
<tt class="descclassname">bytes.</tt><tt class="descname">translate</tt><big>(</big><em>table</em><span class="optional">[</span>, <em>delete</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#bytes.translate" title="Permalink to this definition">¶</a></dt>
<dt id="bytearray.translate">
<tt class="descclassname">bytearray.</tt><tt class="descname">translate</tt><big>(</big><em>table</em><span class="optional">[</span>, <em>delete</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#bytearray.translate" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the bytes or bytearray object where all bytes occurring in
the optional argument <em>delete</em> are removed, and the remaining bytes have been
mapped through the given translation table, which must be a bytes object of
length 256.</p>
<p>You can use the <a class="reference internal" href="#bytes.maketrans" title="bytes.maketrans"><tt class="xref py py-func docutils literal"><span class="pre">bytes.maketrans()</span></tt></a> method to create a translation table.</p>
<p>Set the <em>table</em> argument to <tt class="xref docutils literal"><span class="pre">None</span></tt> for translations that only delete
characters:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="s">&#39;read this short text&#39;</span><span class="o">.</span><span class="n">translate</span><span class="p">(</span><span class="k">None</span><span class="p">,</span> <span class="n">b</span><span class="s">&#39;aeiou&#39;</span><span class="p">)</span>
<span class="go">b&#39;rd ths shrt txt&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="staticmethod">
<dt id="bytes.maketrans">
<em class="property">static </em><tt class="descclassname">bytes.</tt><tt class="descname">maketrans</tt><big>(</big><em>from</em>, <em>to</em><big>)</big><a class="headerlink" href="#bytes.maketrans" title="Permalink to this definition">¶</a></dt>
<dt id="bytearray.maketrans">
<em class="property">static </em><tt class="descclassname">bytearray.</tt><tt class="descname">maketrans</tt><big>(</big><em>from</em>, <em>to</em><big>)</big><a class="headerlink" href="#bytearray.maketrans" title="Permalink to this definition">¶</a></dt>
<dd><p>This static method returns a translation table usable for
<a class="reference internal" href="#bytes.translate" title="bytes.translate"><tt class="xref py py-meth docutils literal"><span class="pre">bytes.translate()</span></tt></a> that will map each character in <em>from</em> into the
character at the same position in <em>to</em>; <em>from</em> and <em>to</em> must be bytes objects
and have the same length.</p>
<p class="versionadded">
<span class="versionmodified">New in version 3.1.</span> </p>
</dd></dl>

</div>
<div class="section" id="memory-views">
<span id="typememoryview"></span><h3>4.8.4. Memory Views<a class="headerlink" href="#memory-views" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#memoryview" title="memoryview"><tt class="xref py py-class docutils literal"><span class="pre">memoryview</span></tt></a> objects allow Python code to access the internal data
of an object that supports the <a class="reference internal" href="../c-api/buffer.html#bufferobjects"><em>buffer protocol</em></a> without
copying.</p>
<dl class="class">
<dt id="memoryview">
<em class="property">class </em><tt class="descname">memoryview</tt><big>(</big><em>obj</em><big>)</big><a class="headerlink" href="#memoryview" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <a class="reference internal" href="#memoryview" title="memoryview"><tt class="xref py py-class docutils literal"><span class="pre">memoryview</span></tt></a> that references <em>obj</em>.  <em>obj</em> must support the
buffer protocol.  Built-in objects that support the buffer protocol include
<a class="reference internal" href="functions.html#bytes" title="bytes"><tt class="xref py py-class docutils literal"><span class="pre">bytes</span></tt></a> and <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a>.</p>
<p>A <a class="reference internal" href="#memoryview" title="memoryview"><tt class="xref py py-class docutils literal"><span class="pre">memoryview</span></tt></a> has the notion of an <em>element</em>, which is the
atomic memory unit handled by the originating object <em>obj</em>.  For many
simple types such as <a class="reference internal" href="functions.html#bytes" title="bytes"><tt class="xref py py-class docutils literal"><span class="pre">bytes</span></tt></a> and <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a>, an element
is a single byte, but other types such as <a class="reference internal" href="array.html#array.array" title="array.array"><tt class="xref py py-class docutils literal"><span class="pre">array.array</span></tt></a> may have
bigger elements.</p>
<p><tt class="docutils literal"><span class="pre">len(view)</span></tt> is equal to the length of <a class="reference internal" href="#memoryview.tolist" title="memoryview.tolist"><tt class="xref py py-class docutils literal"><span class="pre">tolist</span></tt></a>.
If <tt class="docutils literal"><span class="pre">view.ndim</span> <span class="pre">=</span> <span class="pre">0</span></tt>, the length is 1. If <tt class="docutils literal"><span class="pre">view.ndim</span> <span class="pre">=</span> <span class="pre">1</span></tt>, the length
is equal to the number of elements in the view. For higher dimensions,
the length is equal to the length of the nested list representation of
the view. The <a class="reference internal" href="#memoryview.itemsize" title="memoryview.itemsize"><tt class="xref py py-class docutils literal"><span class="pre">itemsize</span></tt></a> attribute will give you the
number of bytes in a single element.</p>
<p>A <a class="reference internal" href="#memoryview" title="memoryview"><tt class="xref py py-class docutils literal"><span class="pre">memoryview</span></tt></a> supports slicing to expose its data. If
<a class="reference internal" href="#memoryview.format" title="memoryview.format"><tt class="xref py py-class docutils literal"><span class="pre">format</span></tt></a> is one of the native format specifiers
from the <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><tt class="xref py py-mod docutils literal"><span class="pre">struct</span></tt></a> module, indexing will return a single element
with the correct type. Full slicing will result in a subview:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">v</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;abcefg&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="go">98</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="go">103</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">4</span><span class="p">]</span>
<span class="go">&lt;memory at 0x7f3ddc9f4350&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">bytes</span><span class="p">(</span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">4</span><span class="p">])</span>
<span class="go">b&#39;bce&#39;</span>
</pre></div>
</div>
<p>Other native formats:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s">&#39;l&#39;</span><span class="p">,</span> <span class="p">[</span><span class="o">-</span><span class="mi">11111111</span><span class="p">,</span> <span class="mi">22222222</span><span class="p">,</span> <span class="o">-</span><span class="mi">33333333</span><span class="p">,</span> <span class="mi">44444444</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">-11111111</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="go">44444444</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">3</span><span class="p">]</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[-33333333]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[-11111111, -33333333]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[44444444, -33333333, 22222222, -11111111]</span>
</pre></div>
</div>
<p class="versionadded">
<span class="versionmodified">New in version 3.3.</span> </p>
<p>If the underlying object is writable, the memoryview supports slice
assignment. Resizing is not allowed:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;abcefg&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="o">.</span><span class="n">readonly</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="nb">ord</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;z&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span>
<span class="go">bytearray(b&#39;zbcefg&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">4</span><span class="p">]</span> <span class="o">=</span> <span class="n">b</span><span class="s">&#39;123&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span>
<span class="go">bytearray(b&#39;z123fg&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="n">b</span><span class="s">&#39;spam&#39;</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">&lt;module&gt;</span>
<span class="nc">ValueError: memoryview assignment</span>: <span class="n-Identifier">lvalue and rvalue have different structures</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">6</span><span class="p">]</span> <span class="o">=</span> <span class="n">b</span><span class="s">&#39;spam&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span>
<span class="go">bytearray(b&#39;z1spam&#39;)</span>
</pre></div>
</div>
<p>One-dimensional memoryviews of hashable (read-only) types with formats
&#8216;B&#8217;, &#8216;b&#8217; or &#8216;c&#8217; are also hashable. The hash is defined as
<tt class="docutils literal"><span class="pre">hash(m)</span> <span class="pre">==</span> <span class="pre">hash(m.tobytes())</span></tt>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">v</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;abcefg&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">hash</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;abcefg&#39;</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">hash</span><span class="p">(</span><span class="n">v</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">4</span><span class="p">])</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;ce&#39;</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">hash</span><span class="p">(</span><span class="n">v</span><span class="p">[::</span><span class="o">-</span><span class="mi">2</span><span class="p">])</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;abcefg&#39;</span><span class="p">[::</span><span class="o">-</span><span class="mi">2</span><span class="p">])</span>
<span class="go">True</span>
</pre></div>
</div>
<p class="versionchanged">
<span class="versionmodified">Changed in version 3.3:</span> One-dimensional memoryviews with formats &#8216;B&#8217;, &#8216;b&#8217; or &#8216;c&#8217; are now hashable.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Hashing of memoryviews with formats other than &#8216;B&#8217;, &#8216;b&#8217; or &#8216;c&#8217; as well
as hashing of multi-dimensional memoryviews is possible in version 3.3.0,
but will raise an error in 3.3.1 in order to be compatible with the new
memoryview equality definition.</p>
</div>
<p><a class="reference internal" href="#memoryview" title="memoryview"><tt class="xref py py-class docutils literal"><span class="pre">memoryview</span></tt></a> has several methods:</p>
<dl class="method">
<dt id="memoryview.__eq__">
<tt class="descname">__eq__</tt><big>(</big><em>exporter</em><big>)</big><a class="headerlink" href="#memoryview.__eq__" title="Permalink to this definition">¶</a></dt>
<dd><p>A memoryview and a <span class="target" id="index-36"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-3118"><strong>PEP 3118</strong></a> exporter are equal if their shapes are
equivalent and if all corresponding values are equal when the operands&#8217;
respective format codes are interpreted using <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><tt class="xref py py-mod docutils literal"><span class="pre">struct</span></tt></a> syntax.</p>
<p>For the subset of <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><tt class="xref py py-mod docutils literal"><span class="pre">struct</span></tt></a> format strings currently supported by
<a class="reference internal" href="#memoryview.tolist" title="memoryview.tolist"><tt class="xref py py-meth docutils literal"><span class="pre">tolist()</span></tt></a>, <tt class="docutils literal"><span class="pre">v</span></tt> and <tt class="docutils literal"><span class="pre">w</span></tt> are equal if <tt class="docutils literal"><span class="pre">v.tolist()</span> <span class="pre">==</span> <span class="pre">w.tolist()</span></tt>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s">&#39;I&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s">&#39;d&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">,</span> <span class="mf">3.0</span><span class="p">,</span> <span class="mf">4.0</span><span class="p">,</span> <span class="mf">5.0</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s">&#39;b&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">5</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">==</span> <span class="n">a</span> <span class="o">==</span> <span class="n">y</span> <span class="o">==</span> <span class="n">b</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span> <span class="o">==</span> <span class="n">a</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span> <span class="o">==</span> <span class="n">y</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span> <span class="o">==</span> <span class="n">b</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span> <span class="o">=</span> <span class="n">y</span><span class="p">[::</span><span class="o">-</span><span class="mi">2</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span> <span class="o">==</span> <span class="n">c</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span> <span class="o">==</span> <span class="n">c</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">True</span>
</pre></div>
</div>
<p>If either format string is not supported by the <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><tt class="xref py py-mod docutils literal"><span class="pre">struct</span></tt></a> module,
then the objects will always compare as unequal (even if the format
strings and buffer contents are identical):</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="n">BigEndianStructure</span><span class="p">,</span> <span class="n">c_long</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">BEPoint</span><span class="p">(</span><span class="n">BigEndianStructure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&quot;x&quot;</span><span class="p">,</span> <span class="n">c_long</span><span class="p">),</span> <span class="p">(</span><span class="s">&quot;y&quot;</span><span class="p">,</span> <span class="n">c_long</span><span class="p">)]</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">point</span> <span class="o">=</span> <span class="n">BEPoint</span><span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">point</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">point</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">==</span> <span class="n">point</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">==</span> <span class="n">b</span>
<span class="go">False</span>
</pre></div>
</div>
<p>Note that, as with floating point numbers, <tt class="docutils literal"><span class="pre">v</span> <span class="pre">is</span> <span class="pre">w</span></tt> does <em>not</em> imply
<tt class="docutils literal"><span class="pre">v</span> <span class="pre">==</span> <span class="pre">w</span></tt> for memoryview objects.</p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 3.3:</span> Previous versions compared the raw memory disregarding the item format
and the logical array structure.</p>
</dd></dl>

<dl class="method">
<dt id="memoryview.tobytes">
<tt class="descname">tobytes</tt><big>(</big><big>)</big><a class="headerlink" href="#memoryview.tobytes" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the data in the buffer as a bytestring.  This is equivalent to
calling the <a class="reference internal" href="functions.html#bytes" title="bytes"><tt class="xref py py-class docutils literal"><span class="pre">bytes</span></tt></a> constructor on the memoryview.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;abc&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">tobytes</span><span class="p">()</span>
<span class="go">b&#39;abc&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">bytes</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
<span class="go">b&#39;abc&#39;</span>
</pre></div>
</div>
<p>For non-contiguous arrays the result is equal to the flattened list
representation with all elements converted to bytes. <a class="reference internal" href="#memoryview.tobytes" title="memoryview.tobytes"><tt class="xref py py-meth docutils literal"><span class="pre">tobytes()</span></tt></a>
supports all format strings, including those that are not in
<a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><tt class="xref py py-mod docutils literal"><span class="pre">struct</span></tt></a> module syntax.</p>
</dd></dl>

<dl class="method">
<dt id="memoryview.tolist">
<tt class="descname">tolist</tt><big>(</big><big>)</big><a class="headerlink" href="#memoryview.tolist" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the data in the buffer as a list of elements.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">memoryview</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;abc&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[97, 98, 99]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s">&#39;d&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mf">1.1</span><span class="p">,</span> <span class="mf">2.2</span><span class="p">,</span> <span class="mf">3.3</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[1.1, 2.2, 3.3]</span>
</pre></div>
</div>
<p class="versionchanged">
<span class="versionmodified">Changed in version 3.3:</span> <a class="reference internal" href="#memoryview.tolist" title="memoryview.tolist"><tt class="xref py py-meth docutils literal"><span class="pre">tolist()</span></tt></a> now supports all single character native formats in
<a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><tt class="xref py py-mod docutils literal"><span class="pre">struct</span></tt></a> module syntax as well as multi-dimensional
representations.</p>
</dd></dl>

<dl class="method">
<dt id="memoryview.release">
<tt class="descname">release</tt><big>(</big><big>)</big><a class="headerlink" href="#memoryview.release" title="Permalink to this definition">¶</a></dt>
<dd><p>Release the underlying buffer exposed by the memoryview object.  Many
objects take special actions when a view is held on them (for example,
a <a class="reference internal" href="functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a> would temporarily forbid resizing); therefore,
calling release() is handy to remove these restrictions (and free any
dangling resources) as soon as possible.</p>
<p>After this method has been called, any further operation on the view
raises a <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-class docutils literal"><span class="pre">ValueError</span></tt></a> (except <a class="reference internal" href="#memoryview.release" title="memoryview.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a> itself which can
be called multiple times):</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;abc&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">&lt;module&gt;</span>
<span class="nc">ValueError</span>: <span class="n-Identifier">operation forbidden on released memoryview object</span>
</pre></div>
</div>
<p>The context management protocol can be used for a similar effect,
using the <tt class="docutils literal"><span class="pre">with</span></tt> statement:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;abc&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">m</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gp">...</span>
<span class="go">97</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">&lt;module&gt;</span>
<span class="nc">ValueError</span>: <span class="n-Identifier">operation forbidden on released memoryview object</span>
</pre></div>
</div>
<p class="versionadded">
<span class="versionmodified">New in version 3.2.</span> </p>
</dd></dl>

<dl class="method">
<dt id="memoryview.cast">
<tt class="descname">cast</tt><big>(</big><em>format</em><span class="optional">[</span>, <em>shape</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#memoryview.cast" title="Permalink to this definition">¶</a></dt>
<dd><p>Cast a memoryview to a new format or shape. <em>shape</em> defaults to
<tt class="docutils literal"><span class="pre">[byte_length//new_itemsize]</span></tt>, which means that the result view
will be one-dimensional. The return value is a new memoryview, but
the buffer itself is not copied. Supported casts are 1D -&gt; C-contiguous
and C-contiguous -&gt; 1D.</p>
<p>Both formats are restricted to single element native formats in
<a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><tt class="xref py py-mod docutils literal"><span class="pre">struct</span></tt></a> syntax. One of the formats must be a byte format
(&#8216;B&#8217;, &#8216;b&#8217; or &#8216;c&#8217;). The byte length of the result must be the same
as the original length.</p>
<p>Cast 1D/long to 1D/unsigned bytes:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s">&#39;l&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">format</span>
<span class="go">&#39;l&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">itemsize</span>
<span class="go">8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">24</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="s">&#39;B&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">format</span>
<span class="go">&#39;B&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">itemsize</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="go">24</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">24</span>
</pre></div>
</div>
<p>Cast 1D/unsigned bytes to 1D/char:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;zyz&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="n">b</span><span class="s">&#39;a&#39;</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">&lt;module&gt;</span>
<span class="nc">ValueError: memoryview</span>: <span class="n-Identifier">invalid value for format &quot;B&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="s">&#39;c&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="n">b</span><span class="s">&#39;a&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
<span class="go">bytearray(b&#39;ayz&#39;)</span>
</pre></div>
</div>
<p>Cast 1D/bytes to 3D/ints to 1D/signed char:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">struct</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">buf</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="s">&quot;i&quot;</span><span class="o">*</span><span class="mi">12</span><span class="p">,</span> <span class="o">*</span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">12</span><span class="p">)))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">buf</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="s">&#39;i&#39;</span><span class="p">,</span> <span class="n">shape</span><span class="o">=</span><span class="p">[</span><span class="mi">2</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">format</span>
<span class="go">&#39;i&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">itemsize</span>
<span class="go">4</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">48</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span> <span class="o">=</span> <span class="n">y</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="s">&#39;b&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span><span class="o">.</span><span class="n">format</span>
<span class="go">&#39;b&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span><span class="o">.</span><span class="n">itemsize</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">z</span><span class="p">)</span>
<span class="go">48</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">48</span>
</pre></div>
</div>
<p>Cast 1D/unsigned char to to 2D/unsigned long:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">buf</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="s">&quot;L&quot;</span><span class="o">*</span><span class="mi">6</span><span class="p">,</span> <span class="o">*</span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">6</span><span class="p">)))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">buf</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="s">&#39;L&#39;</span><span class="p">,</span> <span class="n">shape</span><span class="o">=</span><span class="p">[</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">48</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[[0, 1, 2], [3, 4, 5]]</span>
</pre></div>
</div>
<p class="versionadded">
<span class="versionmodified">New in version 3.3.</span> </p>
</dd></dl>

<p>There are also several readonly attributes available:</p>
<dl class="attribute">
<dt id="memoryview.obj">
<tt class="descname">obj</tt><a class="headerlink" href="#memoryview.obj" title="Permalink to this definition">¶</a></dt>
<dd><p>The underlying object of the memoryview:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>  <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;xyz&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">obj</span> <span class="ow">is</span> <span class="n">b</span>
<span class="go">True</span>
</pre></div>
</div>
<p class="versionadded">
<span class="versionmodified">New in version 3.3.</span> </p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.nbytes">
<tt class="descname">nbytes</tt><a class="headerlink" href="#memoryview.nbytes" title="Permalink to this definition">¶</a></dt>
<dd><p><tt class="docutils literal"><span class="pre">nbytes</span> <span class="pre">==</span> <span class="pre">product(shape)</span> <span class="pre">*</span> <span class="pre">itemsize</span> <span class="pre">==</span> <span class="pre">len(m.tobytes())</span></tt>. This is
the amount of space in bytes that the array would use in a contiguous
representation. It is not necessarily equal to len(m):</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s">&#39;i&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">20</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">m</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">12</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">y</span><span class="o">.</span><span class="n">tobytes</span><span class="p">())</span>
<span class="go">12</span>
</pre></div>
</div>
<p>Multi-dimensional arrays:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">struct</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">buf</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="s">&quot;d&quot;</span><span class="o">*</span><span class="mi">12</span><span class="p">,</span> <span class="o">*</span><span class="p">[</span><span class="mf">1.5</span><span class="o">*</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">12</span><span class="p">)])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">buf</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="s">&#39;d&#39;</span><span class="p">,</span> <span class="n">shape</span><span class="o">=</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="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">nbytes</span>
<span class="go">96</span>
</pre></div>
</div>
<p class="versionadded">
<span class="versionmodified">New in version 3.3.</span> </p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.readonly">
<tt class="descname">readonly</tt><a class="headerlink" href="#memoryview.readonly" title="Permalink to this definition">¶</a></dt>
<dd><p>A bool indicating whether the memory is read only.</p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.format">
<tt class="descname">format</tt><a class="headerlink" href="#memoryview.format" title="Permalink to this definition">¶</a></dt>
<dd><p>A string containing the format (in <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><tt class="xref py py-mod docutils literal"><span class="pre">struct</span></tt></a> module style) for each
element in the view. A memoryview can be created from exporters with
arbitrary format strings, but some methods (e.g. <a class="reference internal" href="#memoryview.tolist" title="memoryview.tolist"><tt class="xref py py-meth docutils literal"><span class="pre">tolist()</span></tt></a>) are
restricted to native single element formats.</p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 3.3:</span> format <tt class="docutils literal"><span class="pre">'B'</span></tt> is now handled according to the struct module syntax.
This means that <tt class="docutils literal"><span class="pre">memoryview(b'abc')[0]</span> <span class="pre">==</span> <span class="pre">b'abc'[0]</span> <span class="pre">==</span> <span class="pre">97</span></tt>.</p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.itemsize">
<tt class="descname">itemsize</tt><a class="headerlink" href="#memoryview.itemsize" title="Permalink to this definition">¶</a></dt>
<dd><p>The size in bytes of each element of the memoryview:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span><span class="o">,</span> <span class="nn">struct</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s">&#39;H&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">32000</span><span class="p">,</span> <span class="mi">32001</span><span class="p">,</span> <span class="mi">32002</span><span class="p">]))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">itemsize</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">32000</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">struct</span><span class="o">.</span><span class="n">calcsize</span><span class="p">(</span><span class="s">&#39;H&#39;</span><span class="p">)</span> <span class="o">==</span> <span class="n">m</span><span class="o">.</span><span class="n">itemsize</span>
<span class="go">True</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.ndim">
<tt class="descname">ndim</tt><a class="headerlink" href="#memoryview.ndim" title="Permalink to this definition">¶</a></dt>
<dd><p>An integer indicating how many dimensions of a multi-dimensional array the
memory represents.</p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.shape">
<tt class="descname">shape</tt><a class="headerlink" href="#memoryview.shape" title="Permalink to this definition">¶</a></dt>
<dd><p>A tuple of integers the length of <a class="reference internal" href="#memoryview.ndim" title="memoryview.ndim"><tt class="xref py py-attr docutils literal"><span class="pre">ndim</span></tt></a> giving the shape of the
memory as a N-dimensional array.</p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.strides">
<tt class="descname">strides</tt><a class="headerlink" href="#memoryview.strides" title="Permalink to this definition">¶</a></dt>
<dd><p>A tuple of integers the length of <a class="reference internal" href="#memoryview.ndim" title="memoryview.ndim"><tt class="xref py py-attr docutils literal"><span class="pre">ndim</span></tt></a> giving the size in bytes to
access each element for each dimension of the array.</p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.suboffsets">
<tt class="descname">suboffsets</tt><a class="headerlink" href="#memoryview.suboffsets" title="Permalink to this definition">¶</a></dt>
<dd><p>Used internally for PIL-style arrays. The value is informational only.</p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.c_contiguous">
<tt class="descname">c_contiguous</tt><a class="headerlink" href="#memoryview.c_contiguous" title="Permalink to this definition">¶</a></dt>
<dd><p>A bool indicating whether the memory is C-contiguous.</p>
<p class="versionadded">
<span class="versionmodified">New in version 3.3.</span> </p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.f_contiguous">
<tt class="descname">f_contiguous</tt><a class="headerlink" href="#memoryview.f_contiguous" title="Permalink to this definition">¶</a></dt>
<dd><p>A bool indicating whether the memory is Fortran contiguous.</p>
<p class="versionadded">
<span class="versionmodified">New in version 3.3.</span> </p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.contiguous">
<tt class="descname">contiguous</tt><a class="headerlink" href="#memoryview.contiguous" title="Permalink to this definition">¶</a></dt>
<dd><p>A bool indicating whether the memory is contiguous.</p>
<p class="versionadded">
<span class="versionmodified">New in version 3.3.</span> </p>
</dd></dl>

</dd></dl>

</div>
</div>
<div class="section" id="set-types-set-frozenset">
<span id="types-set"></span><h2>4.9. Set Types &#8212; <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a>, <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a><a class="headerlink" href="#set-types-set-frozenset" title="Permalink to this headline">¶</a></h2>
<p id="index-37">A <em class="dfn">set</em> object is an unordered collection of distinct <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a> objects.
Common uses include membership testing, removing duplicates from a sequence, and
computing mathematical operations such as intersection, union, difference, and
symmetric difference.
(For other containers see the built-in <a class="reference internal" href="#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a>, <a class="reference internal" href="#list" title="list"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a>,
and <a class="reference internal" href="#tuple" title="tuple"><tt class="xref py py-class docutils literal"><span class="pre">tuple</span></tt></a> classes, and the <a class="reference internal" href="collections.html#module-collections" title="collections: Container datatypes"><tt class="xref py py-mod docutils literal"><span class="pre">collections</span></tt></a> module.)</p>
<p>Like other collections, sets support <tt class="docutils literal"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">set</span></tt>, <tt class="docutils literal"><span class="pre">len(set)</span></tt>, and <tt class="docutils literal"><span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span>
<span class="pre">set</span></tt>.  Being an unordered collection, sets do not record element position or
order of insertion.  Accordingly, sets do not support indexing, slicing, or
other sequence-like behavior.</p>
<p>There are currently two built-in set types, <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> and <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a>.
The <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> type is mutable &#8212; the contents can be changed using methods
like <tt class="xref py py-meth docutils literal"><span class="pre">add()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">remove()</span></tt>.  Since it is mutable, it has no hash value
and cannot be used as either a dictionary key or as an element of another set.
The <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a> type is immutable and <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a> &#8212; its contents cannot be
altered after it is created; it can therefore be used as a dictionary key or as
an element of another set.</p>
<p>Non-empty sets (not frozensets) can be created by placing a comma-separated list
of elements within braces, for example: <tt class="docutils literal"><span class="pre">{'jack',</span> <span class="pre">'sjoerd'}</span></tt>, in addition to the
<a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> constructor.</p>
<p>The constructors for both classes work the same:</p>
<dl class="class">
<dt id="set">
<em class="property">class </em><tt class="descname">set</tt><big>(</big><span class="optional">[</span><em>iterable</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#set" title="Permalink to this definition">¶</a></dt>
<dt id="frozenset">
<em class="property">class </em><tt class="descname">frozenset</tt><big>(</big><span class="optional">[</span><em>iterable</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#frozenset" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new set or frozenset object whose elements are taken from
<em>iterable</em>.  The elements of a set must be hashable.  To represent sets of
sets, the inner sets must be <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a> objects.  If <em>iterable</em> is
not specified, a new empty set is returned.</p>
<p>Instances of <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> and <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a> provide the following
operations:</p>
<dl class="describe">
<dt>
<tt class="descname">len(s)</tt></dt>
<dd><p>Return the cardinality of set <em>s</em>.</p>
</dd></dl>

<dl class="describe">
<dt>
<tt class="descname">x in s</tt></dt>
<dd><p>Test <em>x</em> for membership in <em>s</em>.</p>
</dd></dl>

<dl class="describe">
<dt>
<tt class="descname">x not in s</tt></dt>
<dd><p>Test <em>x</em> for non-membership in <em>s</em>.</p>
</dd></dl>

<dl class="method">
<dt id="set.isdisjoint">
<tt class="descname">isdisjoint</tt><big>(</big><em>other</em><big>)</big><a class="headerlink" href="#set.isdisjoint" title="Permalink to this definition">¶</a></dt>
<dd><p>Return True if the set has no elements in common with <em>other</em>.  Sets are
disjoint if and only if their intersection is the empty set.</p>
</dd></dl>

<dl class="method">
<dt id="set.issubset">
<tt class="descname">issubset</tt><big>(</big><em>other</em><big>)</big><a class="headerlink" href="#set.issubset" title="Permalink to this definition">¶</a></dt>
<dt>
<tt class="descname">set &lt;= other</tt></dt>
<dd><p>Test whether every element in the set is in <em>other</em>.</p>
</dd></dl>

<dl class="method">
<dt>
<tt class="descname">set &lt; other</tt></dt>
<dd><p>Test whether the set is a true subset of <em>other</em>, that is,
<tt class="docutils literal"><span class="pre">set</span> <span class="pre">&lt;=</span> <span class="pre">other</span> <span class="pre">and</span> <span class="pre">set</span> <span class="pre">!=</span> <span class="pre">other</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="set.issuperset">
<tt class="descname">issuperset</tt><big>(</big><em>other</em><big>)</big><a class="headerlink" href="#set.issuperset" title="Permalink to this definition">¶</a></dt>
<dt>
<tt class="descname">set &gt;= other</tt></dt>
<dd><p>Test whether every element in <em>other</em> is in the set.</p>
</dd></dl>

<dl class="method">
<dt>
<tt class="descname">set &gt; other</tt></dt>
<dd><p>Test whether the set is a true superset of <em>other</em>, that is, <tt class="docutils literal"><span class="pre">set</span> <span class="pre">&gt;=</span>
<span class="pre">other</span> <span class="pre">and</span> <span class="pre">set</span> <span class="pre">!=</span> <span class="pre">other</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="set.union">
<tt class="descname">union</tt><big>(</big><em>other</em>, <em>...</em><big>)</big><a class="headerlink" href="#set.union" title="Permalink to this definition">¶</a></dt>
<dt>
<tt class="descname">set | other | ...</tt></dt>
<dd><p>Return a new set with elements from the set and all others.</p>
</dd></dl>

<dl class="method">
<dt id="set.intersection">
<tt class="descname">intersection</tt><big>(</big><em>other</em>, <em>...</em><big>)</big><a class="headerlink" href="#set.intersection" title="Permalink to this definition">¶</a></dt>
<dt>
<tt class="descname">set &amp; other &amp; ...</tt></dt>
<dd><p>Return a new set with elements common to the set and all others.</p>
</dd></dl>

<dl class="method">
<dt id="set.difference">
<tt class="descname">difference</tt><big>(</big><em>other</em>, <em>...</em><big>)</big><a class="headerlink" href="#set.difference" title="Permalink to this definition">¶</a></dt>
<dt>
<tt class="descname">set - other - ...</tt></dt>
<dd><p>Return a new set with elements in the set that are not in the others.</p>
</dd></dl>

<dl class="method">
<dt id="set.symmetric_difference">
<tt class="descname">symmetric_difference</tt><big>(</big><em>other</em><big>)</big><a class="headerlink" href="#set.symmetric_difference" title="Permalink to this definition">¶</a></dt>
<dt>
<tt class="descname">set ^ other</tt></dt>
<dd><p>Return a new set with elements in either the set or <em>other</em> but not both.</p>
</dd></dl>

<dl class="method">
<dt id="set.copy">
<tt class="descname">copy</tt><big>(</big><big>)</big><a class="headerlink" href="#set.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new set with a shallow copy of <em>s</em>.</p>
</dd></dl>

<p>Note, the non-operator versions of <a class="reference internal" href="#set.union" title="set.union"><tt class="xref py py-meth docutils literal"><span class="pre">union()</span></tt></a>, <a class="reference internal" href="#set.intersection" title="set.intersection"><tt class="xref py py-meth docutils literal"><span class="pre">intersection()</span></tt></a>,
<a class="reference internal" href="#set.difference" title="set.difference"><tt class="xref py py-meth docutils literal"><span class="pre">difference()</span></tt></a>, and <a class="reference internal" href="#set.symmetric_difference" title="set.symmetric_difference"><tt class="xref py py-meth docutils literal"><span class="pre">symmetric_difference()</span></tt></a>, <a class="reference internal" href="#set.issubset" title="set.issubset"><tt class="xref py py-meth docutils literal"><span class="pre">issubset()</span></tt></a>, and
<a class="reference internal" href="#set.issuperset" title="set.issuperset"><tt class="xref py py-meth docutils literal"><span class="pre">issuperset()</span></tt></a> methods will accept any iterable as an argument.  In
contrast, their operator based counterparts require their arguments to be
sets.  This precludes error-prone constructions like <tt class="docutils literal"><span class="pre">set('abc')</span> <span class="pre">&amp;</span> <span class="pre">'cbs'</span></tt>
in favor of the more readable <tt class="docutils literal"><span class="pre">set('abc').intersection('cbs')</span></tt>.</p>
<p>Both <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> and <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a> support set to set comparisons. Two
sets are equal if and only if every element of each set is contained in the
other (each is a subset of the other). A set is less than another set if and
only if the first set is a proper subset of the second set (is a subset, but
is not equal). A set is greater than another set if and only if the first set
is a proper superset of the second set (is a superset, but is not equal).</p>
<p>Instances of <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> are compared to instances of <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a>
based on their members.  For example, <tt class="docutils literal"><span class="pre">set('abc')</span> <span class="pre">==</span> <span class="pre">frozenset('abc')</span></tt>
returns <tt class="xref docutils literal"><span class="pre">True</span></tt> and so does <tt class="docutils literal"><span class="pre">set('abc')</span> <span class="pre">in</span> <span class="pre">set([frozenset('abc')])</span></tt>.</p>
<p>The subset and equality comparisons do not generalize to a complete ordering
function.  For example, any two disjoint sets are not equal and are not
subsets of each other, so <em>all</em> of the following return <tt class="xref docutils literal"><span class="pre">False</span></tt>: <tt class="docutils literal"><span class="pre">a&lt;b</span></tt>,
<tt class="docutils literal"><span class="pre">a==b</span></tt>, or <tt class="docutils literal"><span class="pre">a&gt;b</span></tt>.</p>
<p>Since sets only define partial ordering (subset relationships), the output of
the <a class="reference internal" href="#list.sort" title="list.sort"><tt class="xref py py-meth docutils literal"><span class="pre">list.sort()</span></tt></a> method is undefined for lists of sets.</p>
<p>Set elements, like dictionary keys, must be <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a>.</p>
<p>Binary operations that mix <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> instances with <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a>
return the type of the first operand.  For example: <tt class="docutils literal"><span class="pre">frozenset('ab')</span> <span class="pre">|</span>
<span class="pre">set('bc')</span></tt> returns an instance of <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a>.</p>
<p>The following table lists operations available for <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> that do not
apply to immutable instances of <a class="reference internal" href="#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a>:</p>
<dl class="method">
<dt id="set.update">
<tt class="descname">update</tt><big>(</big><em>other</em>, <em>...</em><big>)</big><a class="headerlink" href="#set.update" title="Permalink to this definition">¶</a></dt>
<dt>
<tt class="descname">set |= other | ...</tt></dt>
<dd><p>Update the set, adding elements from all others.</p>
</dd></dl>

<dl class="method">
<dt id="set.intersection_update">
<tt class="descname">intersection_update</tt><big>(</big><em>other</em>, <em>...</em><big>)</big><a class="headerlink" href="#set.intersection_update" title="Permalink to this definition">¶</a></dt>
<dt>
<tt class="descname">set &amp;= other &amp; ...</tt></dt>
<dd><p>Update the set, keeping only elements found in it and all others.</p>
</dd></dl>

<dl class="method">
<dt id="set.difference_update">
<tt class="descname">difference_update</tt><big>(</big><em>other</em>, <em>...</em><big>)</big><a class="headerlink" href="#set.difference_update" title="Permalink to this definition">¶</a></dt>
<dt>
<tt class="descname">set -= other | ...</tt></dt>
<dd><p>Update the set, removing elements found in others.</p>
</dd></dl>

<dl class="method">
<dt id="set.symmetric_difference_update">
<tt class="descname">symmetric_difference_update</tt><big>(</big><em>other</em><big>)</big><a class="headerlink" href="#set.symmetric_difference_update" title="Permalink to this definition">¶</a></dt>
<dt>
<tt class="descname">set ^= other</tt></dt>
<dd><p>Update the set, keeping only elements found in either set, but not in both.</p>
</dd></dl>

<dl class="method">
<dt id="set.add">
<tt class="descname">add</tt><big>(</big><em>elem</em><big>)</big><a class="headerlink" href="#set.add" title="Permalink to this definition">¶</a></dt>
<dd><p>Add element <em>elem</em> to the set.</p>
</dd></dl>

<dl class="method">
<dt id="set.remove">
<tt class="descname">remove</tt><big>(</big><em>elem</em><big>)</big><a class="headerlink" href="#set.remove" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove element <em>elem</em> from the set.  Raises <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> if <em>elem</em> is
not contained in the set.</p>
</dd></dl>

<dl class="method">
<dt id="set.discard">
<tt class="descname">discard</tt><big>(</big><em>elem</em><big>)</big><a class="headerlink" href="#set.discard" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove element <em>elem</em> from the set if it is present.</p>
</dd></dl>

<dl class="method">
<dt id="set.pop">
<tt class="descname">pop</tt><big>(</big><big>)</big><a class="headerlink" href="#set.pop" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove and return an arbitrary element from the set.  Raises
<a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> if the set is empty.</p>
</dd></dl>

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

<p>Note, the non-operator versions of the <a class="reference internal" href="#set.update" title="set.update"><tt class="xref py py-meth docutils literal"><span class="pre">update()</span></tt></a>,
<a class="reference internal" href="#set.intersection_update" title="set.intersection_update"><tt class="xref py py-meth docutils literal"><span class="pre">intersection_update()</span></tt></a>, <a class="reference internal" href="#set.difference_update" title="set.difference_update"><tt class="xref py py-meth docutils literal"><span class="pre">difference_update()</span></tt></a>, and
<a class="reference internal" href="#set.symmetric_difference_update" title="set.symmetric_difference_update"><tt class="xref py py-meth docutils literal"><span class="pre">symmetric_difference_update()</span></tt></a> methods will accept any iterable as an
argument.</p>
<p>Note, the <em>elem</em> argument to the <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><tt class="xref py py-meth docutils literal"><span class="pre">__contains__()</span></tt></a>, <a class="reference internal" href="#set.remove" title="set.remove"><tt class="xref py py-meth docutils literal"><span class="pre">remove()</span></tt></a>, and
<a class="reference internal" href="#set.discard" title="set.discard"><tt class="xref py py-meth docutils literal"><span class="pre">discard()</span></tt></a> methods may be a set.  To support searching for an equivalent
frozenset, the <em>elem</em> set is temporarily mutated during the search and then
restored.  During the search, the <em>elem</em> set should not be read or mutated
since it does not have a meaningful value.</p>
</dd></dl>

</div>
<div class="section" id="mapping-types-dict">
<span id="typesmapping"></span><h2>4.10. Mapping Types &#8212; <a class="reference internal" href="#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a><a class="headerlink" href="#mapping-types-dict" title="Permalink to this headline">¶</a></h2>
<p id="index-38">A <em class="dfn">mapping</em> object maps <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a> values to arbitrary objects.
Mappings are mutable objects.  There is currently only one standard mapping
type, the <em class="dfn">dictionary</em>.  (For other containers see the built-in
<a class="reference internal" href="#list" title="list"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a>, <a class="reference internal" href="#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a>, and <a class="reference internal" href="#tuple" title="tuple"><tt class="xref py py-class docutils literal"><span class="pre">tuple</span></tt></a> classes, and the
<a class="reference internal" href="collections.html#module-collections" title="collections: Container datatypes"><tt class="xref py py-mod docutils literal"><span class="pre">collections</span></tt></a> module.)</p>
<p>A dictionary&#8217;s keys are <em>almost</em> arbitrary values.  Values that are not
<a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a>, that is, values containing lists, dictionaries or other
mutable types (that are compared by value rather than by object identity) may
not be used as keys.  Numeric types used for keys obey the normal rules for
numeric comparison: if two numbers compare equal (such as <tt class="docutils literal"><span class="pre">1</span></tt> and <tt class="docutils literal"><span class="pre">1.0</span></tt>)
then they can be used interchangeably to index the same dictionary entry.  (Note
however, that since computers store floating-point numbers as approximations it
is usually unwise to use them as dictionary keys.)</p>
<p>Dictionaries can be created by placing a comma-separated list of <tt class="docutils literal"><span class="pre">key:</span> <span class="pre">value</span></tt>
pairs within braces, for example: <tt class="docutils literal"><span class="pre">{'jack':</span> <span class="pre">4098,</span> <span class="pre">'sjoerd':</span> <span class="pre">4127}</span></tt> or <tt class="docutils literal"><span class="pre">{4098:</span>
<span class="pre">'jack',</span> <span class="pre">4127:</span> <span class="pre">'sjoerd'}</span></tt>, or by the <a class="reference internal" href="#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> constructor.</p>
<dl class="class">
<dt id="dict">
<em class="property">class </em><tt class="descname">dict</tt><big>(</big><span class="optional">[</span><em>arg</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#dict" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new dictionary initialized from an optional positional argument or
from a set of keyword arguments.  If no arguments are given, return a new
empty dictionary.  If the positional argument <em>arg</em> is a mapping object,
return a dictionary mapping the same keys to the same values as does the
mapping object.  Otherwise the positional argument must be a sequence, a
container that supports iteration, or an iterator object.  The elements of
the argument must each also be of one of those kinds, and each must in turn
contain exactly two objects.  The first is used as a key in the new
dictionary, and the second as the key&#8217;s value.  If a given key is seen more
than once, the last value associated with it is retained in the new
dictionary.</p>
<p>If keyword arguments are given, the keywords themselves with their associated
values are added as items to the dictionary.  If a key is specified both in
the positional argument and as a keyword argument, the value associated with
the keyword is retained in the dictionary.  For example, these all return a
dictionary equal to <tt class="docutils literal"><span class="pre">{&quot;one&quot;:</span> <span class="pre">1,</span> <span class="pre">&quot;two&quot;:</span> <span class="pre">2}</span></tt>:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">dict(one=1,</span> <span class="pre">two=2)</span></tt></li>
<li><tt class="docutils literal"><span class="pre">dict({'one':</span> <span class="pre">1,</span> <span class="pre">'two':</span> <span class="pre">2})</span></tt></li>
<li><tt class="docutils literal"><span class="pre">dict(zip(('one',</span> <span class="pre">'two'),</span> <span class="pre">(1,</span> <span class="pre">2)))</span></tt></li>
<li><tt class="docutils literal"><span class="pre">dict([['two',</span> <span class="pre">2],</span> <span class="pre">['one',</span> <span class="pre">1]])</span></tt></li>
</ul>
<p>The first example only works for keys that are valid Python identifiers; the
others work with any valid keys.</p>
<p>These are the operations that dictionaries support (and therefore, custom
mapping types should support too):</p>
<dl class="describe">
<dt>
<tt class="descname">len(d)</tt></dt>
<dd><p>Return the number of items in the dictionary <em>d</em>.</p>
</dd></dl>

<dl class="describe">
<dt>
<tt class="descname">d[key]</tt></dt>
<dd><p>Return the item of <em>d</em> with key <em>key</em>.  Raises a <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> if <em>key</em> is
not in the map.</p>
<p>If a subclass of dict defines a method <tt class="xref py py-meth docutils literal"><span class="pre">__missing__()</span></tt>, if the key <em>key</em>
is not present, the <tt class="docutils literal"><span class="pre">d[key]</span></tt> operation calls that method with the key <em>key</em>
as argument.  The <tt class="docutils literal"><span class="pre">d[key]</span></tt> operation then returns or raises whatever is
returned or raised by the <tt class="docutils literal"><span class="pre">__missing__(key)</span></tt> call if the key is not
present. No other operations or methods invoke <tt class="xref py py-meth docutils literal"><span class="pre">__missing__()</span></tt>. If
<tt class="xref py py-meth docutils literal"><span class="pre">__missing__()</span></tt> is not defined, <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> is raised.
<tt class="xref py py-meth docutils literal"><span class="pre">__missing__()</span></tt> must be a method; it cannot be an instance variable:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Counter</span><span class="p">(</span><span class="nb">dict</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__missing__</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="gp">... </span>        <span class="k">return</span> <span class="mi">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s">&#39;red&#39;</span><span class="p">]</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s">&#39;red&#39;</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s">&#39;red&#39;</span><span class="p">]</span>
<span class="go">1</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="collections.html#collections.Counter" title="collections.Counter"><tt class="xref py py-class docutils literal"><span class="pre">collections.Counter</span></tt></a> for a complete implementation including
other methods helpful for accumulating and managing tallies.</p>
</dd></dl>

<dl class="describe">
<dt>
<tt class="descname">d[key] = value</tt></dt>
<dd><p>Set <tt class="docutils literal"><span class="pre">d[key]</span></tt> to <em>value</em>.</p>
</dd></dl>

<dl class="describe">
<dt>
<tt class="descname">del d[key]</tt></dt>
<dd><p>Remove <tt class="docutils literal"><span class="pre">d[key]</span></tt> from <em>d</em>.  Raises a <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> if <em>key</em> is not in the
map.</p>
</dd></dl>

<dl class="describe">
<dt>
<tt class="descname">key in d</tt></dt>
<dd><p>Return <tt class="xref docutils literal"><span class="pre">True</span></tt> if <em>d</em> has a key <em>key</em>, else <tt class="xref docutils literal"><span class="pre">False</span></tt>.</p>
</dd></dl>

<dl class="describe">
<dt>
<tt class="descname">key not in d</tt></dt>
<dd><p>Equivalent to <tt class="docutils literal"><span class="pre">not</span> <span class="pre">key</span> <span class="pre">in</span> <span class="pre">d</span></tt>.</p>
</dd></dl>

<dl class="describe">
<dt>
<tt class="descname">iter(d)</tt></dt>
<dd><p>Return an iterator over the keys of the dictionary.  This is a shortcut
for <tt class="docutils literal"><span class="pre">iter(d.keys())</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.clear">
<tt class="descname">clear</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove all items from the dictionary.</p>
</dd></dl>

<dl class="method">
<dt id="dict.copy">
<tt class="descname">copy</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a shallow copy of the dictionary.</p>
</dd></dl>

<dl class="classmethod">
<dt id="dict.fromkeys">
<em class="property">classmethod </em><tt class="descname">fromkeys</tt><big>(</big><em>seq</em><span class="optional">[</span>, <em>value</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#dict.fromkeys" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new dictionary with keys from <em>seq</em> and values set to <em>value</em>.</p>
<p><a class="reference internal" href="#dict.fromkeys" title="dict.fromkeys"><tt class="xref py py-meth docutils literal"><span class="pre">fromkeys()</span></tt></a> is a class method that returns a new dictionary. <em>value</em>
defaults to <tt class="xref docutils literal"><span class="pre">None</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.get">
<tt class="descname">get</tt><big>(</big><em>key</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#dict.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value for <em>key</em> if <em>key</em> is in the dictionary, else <em>default</em>.
If <em>default</em> is not given, it defaults to <tt class="xref docutils literal"><span class="pre">None</span></tt>, so that this method
never raises a <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.items">
<tt class="descname">items</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.items" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new view of the dictionary&#8217;s items (<tt class="docutils literal"><span class="pre">(key,</span> <span class="pre">value)</span></tt> pairs).
See the <a class="reference internal" href="#dict-views"><em>documentation of view objects</em></a>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.keys">
<tt class="descname">keys</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.keys" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new view of the dictionary&#8217;s keys.  See the <a class="reference internal" href="#dict-views"><em>documentation
of view objects</em></a>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.pop">
<tt class="descname">pop</tt><big>(</big><em>key</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#dict.pop" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>key</em> is in the dictionary, remove it and return its value, else return
<em>default</em>.  If <em>default</em> is not given and <em>key</em> is not in the dictionary,
a <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> is raised.</p>
</dd></dl>

<dl class="method">
<dt id="dict.popitem">
<tt class="descname">popitem</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.popitem" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove and return an arbitrary <tt class="docutils literal"><span class="pre">(key,</span> <span class="pre">value)</span></tt> pair from the dictionary.</p>
<p><a class="reference internal" href="#dict.popitem" title="dict.popitem"><tt class="xref py py-meth docutils literal"><span class="pre">popitem()</span></tt></a> is useful to destructively iterate over a dictionary, as
often used in set algorithms.  If the dictionary is empty, calling
<a class="reference internal" href="#dict.popitem" title="dict.popitem"><tt class="xref py py-meth docutils literal"><span class="pre">popitem()</span></tt></a> raises a <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.setdefault">
<tt class="descname">setdefault</tt><big>(</big><em>key</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#dict.setdefault" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>key</em> is in the dictionary, return its value.  If not, insert <em>key</em>
with a value of <em>default</em> and return <em>default</em>.  <em>default</em> defaults to
<tt class="xref docutils literal"><span class="pre">None</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.update">
<tt class="descname">update</tt><big>(</big><span class="optional">[</span><em>other</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#dict.update" title="Permalink to this definition">¶</a></dt>
<dd><p>Update the dictionary with the key/value pairs from <em>other</em>, overwriting
existing keys.  Return <tt class="xref docutils literal"><span class="pre">None</span></tt>.</p>
<p><a class="reference internal" href="#dict.update" title="dict.update"><tt class="xref py py-meth docutils literal"><span class="pre">update()</span></tt></a> accepts either another dictionary object or an iterable of
key/value pairs (as tuples or other iterables of length two).  If keyword
arguments are specified, the dictionary is then updated with those
key/value pairs: <tt class="docutils literal"><span class="pre">d.update(red=1,</span> <span class="pre">blue=2)</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.values">
<tt class="descname">values</tt><big>(</big><big>)</big><a class="headerlink" href="#dict.values" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new view of the dictionary&#8217;s values.  See the
<a class="reference internal" href="#dict-views"><em>documentation of view objects</em></a>.</p>
</dd></dl>

</dd></dl>

<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="types.html#types.MappingProxyType" title="types.MappingProxyType"><tt class="xref py py-class docutils literal"><span class="pre">types.MappingProxyType</span></tt></a> can be used to create a read-only view
of a <a class="reference internal" href="#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a>.</p>
</div>
<div class="section" id="dictionary-view-objects">
<span id="dict-views"></span><h3>4.10.1. Dictionary view objects<a class="headerlink" href="#dictionary-view-objects" title="Permalink to this headline">¶</a></h3>
<p>The objects returned by <a class="reference internal" href="#dict.keys" title="dict.keys"><tt class="xref py py-meth docutils literal"><span class="pre">dict.keys()</span></tt></a>, <a class="reference internal" href="#dict.values" title="dict.values"><tt class="xref py py-meth docutils literal"><span class="pre">dict.values()</span></tt></a> and
<a class="reference internal" href="#dict.items" title="dict.items"><tt class="xref py py-meth docutils literal"><span class="pre">dict.items()</span></tt></a> are <em>view objects</em>.  They provide a dynamic view on the
dictionary&#8217;s entries, which means that when the dictionary changes, the view
reflects these changes.</p>
<p>Dictionary views can be iterated over to yield their respective data, and
support membership tests:</p>
<dl class="describe">
<dt>
<tt class="descname">len(dictview)</tt></dt>
<dd><p>Return the number of entries in the dictionary.</p>
</dd></dl>

<dl class="describe">
<dt>
<tt class="descname">iter(dictview)</tt></dt>
<dd><p>Return an iterator over the keys, values or items (represented as tuples of
<tt class="docutils literal"><span class="pre">(key,</span> <span class="pre">value)</span></tt>) in the dictionary.</p>
<p>Keys and values are iterated over in an arbitrary order which is non-random,
varies across Python implementations, and depends on the dictionary&#8217;s history
of insertions and deletions. If keys, values and items views are iterated
over with no intervening modifications to the dictionary, the order of items
will directly correspond.  This allows the creation of <tt class="docutils literal"><span class="pre">(value,</span> <span class="pre">key)</span></tt> pairs
using <a class="reference internal" href="functions.html#zip" title="zip"><tt class="xref py py-func docutils literal"><span class="pre">zip()</span></tt></a>: <tt class="docutils literal"><span class="pre">pairs</span> <span class="pre">=</span> <span class="pre">zip(d.values(),</span> <span class="pre">d.keys())</span></tt>.  Another way to
create the same list is <tt class="docutils literal"><span class="pre">pairs</span> <span class="pre">=</span> <span class="pre">[(v,</span> <span class="pre">k)</span> <span class="pre">for</span> <span class="pre">(k,</span> <span class="pre">v)</span> <span class="pre">in</span> <span class="pre">d.items()]</span></tt>.</p>
<p>Iterating views while adding or deleting entries in the dictionary may raise
a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> or fail to iterate over all entries.</p>
</dd></dl>

<dl class="describe">
<dt>
<tt class="descname">x in dictview</tt></dt>
<dd><p>Return <tt class="xref docutils literal"><span class="pre">True</span></tt> if <em>x</em> is in the underlying dictionary&#8217;s keys, values or
items (in the latter case, <em>x</em> should be a <tt class="docutils literal"><span class="pre">(key,</span> <span class="pre">value)</span></tt> tuple).</p>
</dd></dl>

<p>Keys views are set-like since their entries are unique and hashable.  If all
values are hashable, so that <tt class="docutils literal"><span class="pre">(key,</span> <span class="pre">value)</span></tt> pairs are unique and hashable,
then the items view is also set-like.  (Values views are not treated as set-like
since the entries are generally not unique.)  For set-like views, all of the
operations defined for the abstract base class <a class="reference internal" href="collections.abc.html#collections.abc.Set" title="collections.abc.Set"><tt class="xref py py-class docutils literal"><span class="pre">collections.abc.Set</span></tt></a> are
available (for example, <tt class="docutils literal"><span class="pre">==</span></tt>, <tt class="docutils literal"><span class="pre">&lt;</span></tt>, or <tt class="docutils literal"><span class="pre">^</span></tt>).</p>
<p>An example of dictionary view usage:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">dishes</span> <span class="o">=</span> <span class="p">{</span><span class="s">&#39;eggs&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s">&#39;sausage&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s">&#39;bacon&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s">&#39;spam&#39;</span><span class="p">:</span> <span class="mi">500</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">keys</span> <span class="o">=</span> <span class="n">dishes</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span> <span class="o">=</span> <span class="n">dishes</span><span class="o">.</span><span class="n">values</span><span class="p">()</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c"># iteration</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">=</span> <span class="mi">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">val</span> <span class="ow">in</span> <span class="n">values</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">n</span> <span class="o">+=</span> <span class="n">val</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="go">504</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c"># keys and values are iterated over in the same order</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">keys</span><span class="p">)</span>
<span class="go">[&#39;eggs&#39;, &#39;bacon&#39;, &#39;sausage&#39;, &#39;spam&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">values</span><span class="p">)</span>
<span class="go">[2, 1, 1, 500]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c"># view objects are dynamic and reflect dict changes</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">dishes</span><span class="p">[</span><span class="s">&#39;eggs&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">dishes</span><span class="p">[</span><span class="s">&#39;sausage&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">keys</span><span class="p">)</span>
<span class="go">[&#39;spam&#39;, &#39;bacon&#39;]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c"># set operations</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">keys</span> <span class="o">&amp;</span> <span class="p">{</span><span class="s">&#39;eggs&#39;</span><span class="p">,</span> <span class="s">&#39;bacon&#39;</span><span class="p">,</span> <span class="s">&#39;salad&#39;</span><span class="p">}</span>
<span class="go">{&#39;bacon&#39;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">keys</span> <span class="o">^</span> <span class="p">{</span><span class="s">&#39;sausage&#39;</span><span class="p">,</span> <span class="s">&#39;juice&#39;</span><span class="p">}</span>
<span class="go">{&#39;juice&#39;, &#39;sausage&#39;, &#39;bacon&#39;, &#39;spam&#39;}</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="context-manager-types">
<span id="typecontextmanager"></span><h2>4.11. Context Manager Types<a class="headerlink" href="#context-manager-types" title="Permalink to this headline">¶</a></h2>
<p id="index-39">Python&#8217;s <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement supports the concept of a runtime context
defined by a context manager.  This is implemented using a pair of methods
that allow user-defined classes to define a runtime context that is entered
before the statement body is executed and exited when the statement ends:</p>
<dl class="method">
<dt id="contextmanager.__enter__">
<tt class="descclassname">contextmanager.</tt><tt class="descname">__enter__</tt><big>(</big><big>)</big><a class="headerlink" href="#contextmanager.__enter__" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter the runtime context and return either this object or another object
related to the runtime context. The value returned by this method is bound to
the identifier in the <a class="reference internal" href="../reference/compound_stmts.html#as"><tt class="xref std std-keyword docutils literal"><span class="pre">as</span></tt></a> clause of <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statements using
this context manager.</p>
<p>An example of a context manager that returns itself is a <a class="reference internal" href="../glossary.html#term-file-object"><em class="xref std std-term">file object</em></a>.
File objects return themselves from __enter__() to allow <a class="reference internal" href="functions.html#open" title="open"><tt class="xref py py-func docutils literal"><span class="pre">open()</span></tt></a> to be
used as the context expression in a <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement.</p>
<p>An example of a context manager that returns a related object is the one
returned by <a class="reference internal" href="decimal.html#decimal.localcontext" title="decimal.localcontext"><tt class="xref py py-func docutils literal"><span class="pre">decimal.localcontext()</span></tt></a>. These managers set the active
decimal context to a copy of the original decimal context and then return the
copy. This allows changes to be made to the current decimal context in the body
of the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement without affecting code outside the
<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement.</p>
</dd></dl>

<dl class="method">
<dt id="contextmanager.__exit__">
<tt class="descclassname">contextmanager.</tt><tt class="descname">__exit__</tt><big>(</big><em>exc_type</em>, <em>exc_val</em>, <em>exc_tb</em><big>)</big><a class="headerlink" href="#contextmanager.__exit__" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit the runtime context and return a Boolean flag indicating if any exception
that occurred should be suppressed. If an exception occurred while executing the
body of the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement, the arguments contain the exception type,
value and traceback information. Otherwise, all three arguments are <tt class="xref docutils literal"><span class="pre">None</span></tt>.</p>
<p>Returning a true value from this method will cause the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement
to suppress the exception and continue execution with the statement immediately
following the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement. Otherwise the exception continues
propagating after this method has finished executing. Exceptions that occur
during execution of this method will replace any exception that occurred in the
body of the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement.</p>
<p>The exception passed in should never be reraised explicitly - instead, this
method should return a false value to indicate that the method completed
successfully and does not want to suppress the raised exception. This allows
context management code (such as <tt class="docutils literal"><span class="pre">contextlib.nested</span></tt>) to easily detect whether
or not an <a class="reference internal" href="#contextmanager.__exit__" title="contextmanager.__exit__"><tt class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></tt></a> method has actually failed.</p>
</dd></dl>

<p>Python defines several context managers to support easy thread synchronisation,
prompt closure of files or other objects, and simpler manipulation of the active
decimal arithmetic context. The specific types are not treated specially beyond
their implementation of the context management protocol. See the
<a class="reference internal" href="contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><tt class="xref py py-mod docutils literal"><span class="pre">contextlib</span></tt></a> module for some examples.</p>
<p>Python&#8217;s <a class="reference internal" href="../glossary.html#term-generator"><em class="xref std std-term">generator</em></a>s and the <a class="reference internal" href="contextlib.html#contextlib.contextmanager" title="contextlib.contextmanager"><tt class="xref py py-class docutils literal"><span class="pre">contextlib.contextmanager</span></tt></a> decorator
provide a convenient way to implement these protocols.  If a generator function is
decorated with the <a class="reference internal" href="contextlib.html#contextlib.contextmanager" title="contextlib.contextmanager"><tt class="xref py py-class docutils literal"><span class="pre">contextlib.contextmanager</span></tt></a> decorator, it will return a
context manager implementing the necessary <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><tt class="xref py py-meth docutils literal"><span class="pre">__enter__()</span></tt></a> and
<a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><tt class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></tt></a> methods, rather than the iterator produced by an undecorated
generator function.</p>
<p>Note that there is no specific slot for any of these methods in the type
structure for Python objects in the Python/C API. Extension types wanting to
define these methods must provide them as a normal Python accessible method.
Compared to the overhead of setting up the runtime context, the overhead of a
single class dictionary lookup is negligible.</p>
</div>
<div class="section" id="other-built-in-types">
<span id="typesother"></span><h2>4.12. Other Built-in Types<a class="headerlink" href="#other-built-in-types" title="Permalink to this headline">¶</a></h2>
<p>The interpreter supports several other kinds of objects. Most of these support
only one or two operations.</p>
<div class="section" id="modules">
<span id="typesmodules"></span><h3>4.12.1. Modules<a class="headerlink" href="#modules" title="Permalink to this headline">¶</a></h3>
<p>The only special operation on a module is attribute access: <tt class="docutils literal"><span class="pre">m.name</span></tt>, where
<em>m</em> is a module and <em>name</em> accesses a name defined in <em>m</em>&#8216;s symbol table.
Module attributes can be assigned to.  (Note that the <a class="reference internal" href="../reference/simple_stmts.html#import"><tt class="xref std std-keyword docutils literal"><span class="pre">import</span></tt></a>
statement is not, strictly speaking, an operation on a module object; <tt class="docutils literal"><span class="pre">import</span>
<span class="pre">foo</span></tt> does not require a module object named <em>foo</em> to exist, rather it requires
an (external) <em>definition</em> for a module named <em>foo</em> somewhere.)</p>
<p>A special attribute of every module is <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt>. This is the dictionary
containing the module&#8217;s symbol table. Modifying this dictionary will actually
change the module&#8217;s symbol table, but direct assignment to the <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt>
attribute is not possible (you can write <tt class="docutils literal"><span class="pre">m.__dict__['a']</span> <span class="pre">=</span> <span class="pre">1</span></tt>, which defines
<tt class="docutils literal"><span class="pre">m.a</span></tt> to be <tt class="docutils literal"><span class="pre">1</span></tt>, but you can&#8217;t write <tt class="docutils literal"><span class="pre">m.__dict__</span> <span class="pre">=</span> <span class="pre">{}</span></tt>).  Modifying
<tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt> directly is not recommended.</p>
<p>Modules built into the interpreter are written like this: <tt class="docutils literal"><span class="pre">&lt;module</span> <span class="pre">'sys'</span>
<span class="pre">(built-in)&gt;</span></tt>.  If loaded from a file, they are written as <tt class="docutils literal"><span class="pre">&lt;module</span> <span class="pre">'os'</span> <span class="pre">from</span>
<span class="pre">'/usr/local/lib/pythonX.Y/os.pyc'&gt;</span></tt>.</p>
</div>
<div class="section" id="classes-and-class-instances">
<span id="typesobjects"></span><h3>4.12.2. Classes and Class Instances<a class="headerlink" href="#classes-and-class-instances" title="Permalink to this headline">¶</a></h3>
<p>See <a class="reference internal" href="../reference/datamodel.html#objects"><em>Objects, values and types</em></a> and <a class="reference internal" href="../reference/compound_stmts.html#class"><em>Class definitions</em></a> for these.</p>
</div>
<div class="section" id="functions">
<span id="typesfunctions"></span><h3>4.12.3. Functions<a class="headerlink" href="#functions" title="Permalink to this headline">¶</a></h3>
<p>Function objects are created by function definitions.  The only operation on a
function object is to call it: <tt class="docutils literal"><span class="pre">func(argument-list)</span></tt>.</p>
<p>There are really two flavors of function objects: built-in functions and
user-defined functions.  Both support the same operation (to call the function),
but the implementation is different, hence the different object types.</p>
<p>See <a class="reference internal" href="../reference/compound_stmts.html#function"><em>Function definitions</em></a> for more information.</p>
</div>
<div class="section" id="methods">
<span id="typesmethods"></span><h3>4.12.4. Methods<a class="headerlink" href="#methods" title="Permalink to this headline">¶</a></h3>
<p id="index-40">Methods are functions that are called using the attribute notation. There are
two flavors: built-in methods (such as <tt class="xref py py-meth docutils literal"><span class="pre">append()</span></tt> on lists) and class
instance methods.  Built-in methods are described with the types that support
them.</p>
<p>If you access a method (a function defined in a class namespace) through an
instance, you get a special object: a <em class="dfn">bound method</em> (also called
<em class="dfn">instance method</em>) object. When called, it will add the <tt class="docutils literal"><span class="pre">self</span></tt> argument
to the argument list.  Bound methods have two special read-only attributes:
<tt class="docutils literal"><span class="pre">m.__self__</span></tt> is the object on which the method operates, and <tt class="docutils literal"><span class="pre">m.__func__</span></tt> is
the function implementing the method.  Calling <tt class="docutils literal"><span class="pre">m(arg-1,</span> <span class="pre">arg-2,</span> <span class="pre">...,</span> <span class="pre">arg-n)</span></tt>
is completely equivalent to calling <tt class="docutils literal"><span class="pre">m.__func__(m.__self__,</span> <span class="pre">arg-1,</span> <span class="pre">arg-2,</span> <span class="pre">...,</span>
<span class="pre">arg-n)</span></tt>.</p>
<p>Like function objects, bound method objects support getting arbitrary
attributes.  However, since method attributes are actually stored on the
underlying function object (<tt class="docutils literal"><span class="pre">meth.__func__</span></tt>), setting method attributes on
bound methods is disallowed.  Attempting to set a method attribute results in a
<a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> being raised.  In order to set a method attribute, you need to
explicitly set it on the underlying function object:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">method</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">pass</span>

<span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="n">c</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">__func__</span><span class="o">.</span><span class="n">whoami</span> <span class="o">=</span> <span class="s">&#39;my name is c&#39;</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="../reference/datamodel.html#types"><em>The standard type hierarchy</em></a> for more information.</p>
</div>
<div class="section" id="code-objects">
<span id="bltin-code-objects"></span><h3>4.12.5. Code Objects<a class="headerlink" href="#code-objects" title="Permalink to this headline">¶</a></h3>
<span class="target" id="index-41"></span><p id="index-42">Code objects are used by the implementation to represent &#8220;pseudo-compiled&#8221;
executable Python code such as a function body. They differ from function
objects because they don&#8217;t contain a reference to their global execution
environment.  Code objects are returned by the built-in <a class="reference internal" href="functions.html#compile" title="compile"><tt class="xref py py-func docutils literal"><span class="pre">compile()</span></tt></a> function
and can be extracted from function objects through their <tt class="xref py py-attr docutils literal"><span class="pre">__code__</span></tt>
attribute. See also the <a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><tt class="xref py py-mod docutils literal"><span class="pre">code</span></tt></a> module.</p>
<p id="index-43">A code object can be executed or evaluated by passing it (instead of a source
string) to the <a class="reference internal" href="functions.html#exec" title="exec"><tt class="xref py py-func docutils literal"><span class="pre">exec()</span></tt></a> or <a class="reference internal" href="functions.html#eval" title="eval"><tt class="xref py py-func docutils literal"><span class="pre">eval()</span></tt></a>  built-in functions.</p>
<p>See <a class="reference internal" href="../reference/datamodel.html#types"><em>The standard type hierarchy</em></a> for more information.</p>
</div>
<div class="section" id="type-objects">
<span id="bltin-type-objects"></span><h3>4.12.6. Type Objects<a class="headerlink" href="#type-objects" title="Permalink to this headline">¶</a></h3>
<p id="index-44">Type objects represent the various object types.  An object&#8217;s type is accessed
by the built-in function <a class="reference internal" href="functions.html#type" title="type"><tt class="xref py py-func docutils literal"><span class="pre">type()</span></tt></a>.  There are no special operations on
types.  The standard module <a class="reference internal" href="types.html#module-types" title="types: Names for built-in types."><tt class="xref py py-mod docutils literal"><span class="pre">types</span></tt></a> defines names for all standard built-in
types.</p>
<p>Types are written like this: <tt class="docutils literal"><span class="pre">&lt;class</span> <span class="pre">'int'&gt;</span></tt>.</p>
</div>
<div class="section" id="the-null-object">
<span id="bltin-null-object"></span><h3>4.12.7. The Null Object<a class="headerlink" href="#the-null-object" title="Permalink to this headline">¶</a></h3>
<p>This object is returned by functions that don&#8217;t explicitly return a value.  It
supports no special operations.  There is exactly one null object, named
<tt class="xref docutils literal"><span class="pre">None</span></tt> (a built-in name).  <tt class="docutils literal"><span class="pre">type(None)()</span></tt> produces the same singleton.</p>
<p>It is written as <tt class="xref docutils literal"><span class="pre">None</span></tt>.</p>
</div>
<div class="section" id="the-ellipsis-object">
<span id="bltin-ellipsis-object"></span><h3>4.12.8. The Ellipsis Object<a class="headerlink" href="#the-ellipsis-object" title="Permalink to this headline">¶</a></h3>
<p>This object is commonly used by slicing (see <a class="reference internal" href="../reference/expressions.html#slicings"><em>Slicings</em></a>).  It supports no
special operations.  There is exactly one ellipsis object, named
<a class="reference internal" href="constants.html#Ellipsis" title="Ellipsis"><tt class="xref py py-const docutils literal"><span class="pre">Ellipsis</span></tt></a> (a built-in name).  <tt class="docutils literal"><span class="pre">type(Ellipsis)()</span></tt> produces the
<a class="reference internal" href="constants.html#Ellipsis" title="Ellipsis"><tt class="xref py py-const docutils literal"><span class="pre">Ellipsis</span></tt></a> singleton.</p>
<p>It is written as <tt class="docutils literal"><span class="pre">Ellipsis</span></tt> or <tt class="docutils literal"><span class="pre">...</span></tt>.</p>
</div>
<div class="section" id="the-notimplemented-object">
<span id="bltin-notimplemented-object"></span><h3>4.12.9. The NotImplemented Object<a class="headerlink" href="#the-notimplemented-object" title="Permalink to this headline">¶</a></h3>
<p>This object is returned from comparisons and binary operations when they are
asked to operate on types they don&#8217;t support. See <a class="reference internal" href="../reference/expressions.html#comparisons"><em>Comparisons</em></a> for more
information.  There is exactly one <tt class="docutils literal"><span class="pre">NotImplemented</span></tt> object.
<tt class="docutils literal"><span class="pre">type(NotImplemented)()</span></tt> produces the singleton instance.</p>
<p>It is written as <tt class="docutils literal"><span class="pre">NotImplemented</span></tt>.</p>
</div>
<div class="section" id="boolean-values">
<span id="bltin-boolean-values"></span><h3>4.12.10. Boolean Values<a class="headerlink" href="#boolean-values" title="Permalink to this headline">¶</a></h3>
<p>Boolean values are the two constant objects <tt class="xref docutils literal"><span class="pre">False</span></tt> and <tt class="xref docutils literal"><span class="pre">True</span></tt>.  They are
used to represent truth values (although other values can also be considered
false or true).  In numeric contexts (for example when used as the argument to
an arithmetic operator), they behave like the integers 0 and 1, respectively.
The built-in function <a class="reference internal" href="functions.html#bool" title="bool"><tt class="xref py py-func docutils literal"><span class="pre">bool()</span></tt></a> can be used to convert any value to a
Boolean, if the value can be interpreted as a truth value (see section
<a class="reference internal" href="#truth"><em>Truth Value Testing</em></a> above).</p>
<p id="index-45">They are written as <tt class="xref docutils literal"><span class="pre">False</span></tt> and <tt class="xref docutils literal"><span class="pre">True</span></tt>, respectively.</p>
</div>
<div class="section" id="internal-objects">
<span id="typesinternal"></span><h3>4.12.11. Internal Objects<a class="headerlink" href="#internal-objects" title="Permalink to this headline">¶</a></h3>
<p>See <a class="reference internal" href="../reference/datamodel.html#types"><em>The standard type hierarchy</em></a> for this information.  It describes stack frame objects,
traceback objects, and slice objects.</p>
</div>
</div>
<div class="section" id="special-attributes">
<span id="specialattrs"></span><h2>4.13. Special Attributes<a class="headerlink" href="#special-attributes" title="Permalink to this headline">¶</a></h2>
<p>The implementation adds a few special read-only attributes to several object
types, where they are relevant.  Some of these are not reported by the
<a class="reference internal" href="functions.html#dir" title="dir"><tt class="xref py py-func docutils literal"><span class="pre">dir()</span></tt></a> built-in function.</p>
<dl class="attribute">
<dt id="object.__dict__">
<tt class="descclassname">object.</tt><tt class="descname">__dict__</tt><a class="headerlink" href="#object.__dict__" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary or other mapping object used to store an object&#8217;s (writable)
attributes.</p>
</dd></dl>

<dl class="attribute">
<dt id="instance.__class__">
<tt class="descclassname">instance.</tt><tt class="descname">__class__</tt><a class="headerlink" href="#instance.__class__" title="Permalink to this definition">¶</a></dt>
<dd><p>The class to which a class instance belongs.</p>
</dd></dl>

<dl class="attribute">
<dt id="class.__bases__">
<tt class="descclassname">class.</tt><tt class="descname">__bases__</tt><a class="headerlink" href="#class.__bases__" title="Permalink to this definition">¶</a></dt>
<dd><p>The tuple of base classes of a class object.</p>
</dd></dl>

<dl class="attribute">
<dt id="class.__name__">
<tt class="descclassname">class.</tt><tt class="descname">__name__</tt><a class="headerlink" href="#class.__name__" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the class or type.</p>
</dd></dl>

<dl class="attribute">
<dt id="class.__qualname__">
<tt class="descclassname">class.</tt><tt class="descname">__qualname__</tt><a class="headerlink" href="#class.__qualname__" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="../glossary.html#term-qualified-name"><em class="xref std std-term">qualified name</em></a> of the class or type.</p>
<p class="versionadded">
<span class="versionmodified">New in version 3.3.</span> </p>
</dd></dl>

<dl class="attribute">
<dt id="class.__mro__">
<tt class="descclassname">class.</tt><tt class="descname">__mro__</tt><a class="headerlink" href="#class.__mro__" title="Permalink to this definition">¶</a></dt>
<dd><p>This attribute is a tuple of classes that are considered when looking for
base classes during method resolution.</p>
</dd></dl>

<dl class="method">
<dt id="class.mro">
<tt class="descclassname">class.</tt><tt class="descname">mro</tt><big>(</big><big>)</big><a class="headerlink" href="#class.mro" title="Permalink to this definition">¶</a></dt>
<dd><p>This method can be overridden by a metaclass to customize the method
resolution order for its instances.  It is called at class instantiation, and
its result is stored in <a class="reference internal" href="#class.__mro__" title="class.__mro__"><tt class="xref py py-attr docutils literal"><span class="pre">__mro__</span></tt></a>.</p>
</dd></dl>

<dl class="method">
<dt id="class.__subclasses__">
<tt class="descclassname">class.</tt><tt class="descname">__subclasses__</tt><big>(</big><big>)</big><a class="headerlink" href="#class.__subclasses__" title="Permalink to this definition">¶</a></dt>
<dd><p>Each class keeps a list of weak references to its immediate subclasses.  This
method returns a list of all those references still alive.
Example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">__subclasses__</span><span class="p">()</span>
<span class="go">[&lt;class &#39;bool&#39;&gt;]</span>
</pre></div>
</div>
</dd></dl>

<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id10" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Additional information on these special methods may be found in the Python
Reference Manual (<a class="reference internal" href="../reference/datamodel.html#customization"><em>Basic customization</em></a>).</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id11" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>As a consequence, the list <tt class="docutils literal"><span class="pre">[1,</span> <span class="pre">2]</span></tt> is considered equal to <tt class="docutils literal"><span class="pre">[1.0,</span> <span class="pre">2.0]</span></tt>, and
similarly for tuples.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id12" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label">[3]</td><td>They must have since the parser can&#8217;t tell the type of the operands.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id13" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label">[4]</td><td><em>(<a class="fn-backref" href="#id5">1</a>, <a class="fn-backref" href="#id6">2</a>, <a class="fn-backref" href="#id7">3</a>, <a class="fn-backref" href="#id8">4</a>)</em> Cased characters are those with general category property being one of
&#8220;Lu&#8221; (Letter, uppercase), &#8220;Ll&#8221; (Letter, lowercase), or &#8220;Lt&#8221; (Letter, titlecase).</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id14" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id9">[5]</a></td><td>To format only a tuple you should therefore provide a singleton tuple whose only
element is the tuple to be formatted.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">4. Built-in Types</a><ul>
<li><a class="reference internal" href="#truth-value-testing">4.1. Truth Value Testing</a></li>
<li><a class="reference internal" href="#boolean-operations-and-or-not">4.2. Boolean Operations &#8212; <tt class="docutils literal"><span class="pre">and</span></tt>, <tt class="docutils literal"><span class="pre">or</span></tt>, <tt class="docutils literal"><span class="pre">not</span></tt></a></li>
<li><a class="reference internal" href="#comparisons">4.3. Comparisons</a></li>
<li><a class="reference internal" href="#numeric-types-int-float-complex">4.4. Numeric Types &#8212; <tt class="docutils literal"><span class="pre">int</span></tt>, <tt class="docutils literal"><span class="pre">float</span></tt>, <tt class="docutils literal"><span class="pre">complex</span></tt></a><ul>
<li><a class="reference internal" href="#bitwise-operations-on-integer-types">4.4.1. Bitwise Operations on Integer Types</a></li>
<li><a class="reference internal" href="#additional-methods-on-integer-types">4.4.2. Additional Methods on Integer Types</a></li>
<li><a class="reference internal" href="#additional-methods-on-float">4.4.3. Additional Methods on Float</a></li>
<li><a class="reference internal" href="#hashing-of-numeric-types">4.4.4. Hashing of numeric types</a></li>
</ul>
</li>
<li><a class="reference internal" href="#iterator-types">4.5. Iterator Types</a><ul>
<li><a class="reference internal" href="#generator-types">4.5.1. Generator Types</a></li>
</ul>
</li>
<li><a class="reference internal" href="#sequence-types-list-tuple-range">4.6. Sequence Types &#8212; <tt class="docutils literal"><span class="pre">list</span></tt>, <tt class="docutils literal"><span class="pre">tuple</span></tt>, <tt class="docutils literal"><span class="pre">range</span></tt></a><ul>
<li><a class="reference internal" href="#common-sequence-operations">4.6.1. Common Sequence Operations</a></li>
<li><a class="reference internal" href="#immutable-sequence-types">4.6.2. Immutable Sequence Types</a></li>
<li><a class="reference internal" href="#mutable-sequence-types">4.6.3. Mutable Sequence Types</a></li>
<li><a class="reference internal" href="#lists">4.6.4. Lists</a></li>
<li><a class="reference internal" href="#tuples">4.6.5. Tuples</a></li>
<li><a class="reference internal" href="#ranges">4.6.6. Ranges</a></li>
</ul>
</li>
<li><a class="reference internal" href="#text-sequence-type-str">4.7. Text Sequence Type &#8212; <tt class="docutils literal"><span class="pre">str</span></tt></a><ul>
<li><a class="reference internal" href="#string-methods">4.7.1. String Methods</a></li>
<li><a class="reference internal" href="#printf-style-string-formatting">4.7.2. <tt class="docutils literal"><span class="pre">printf</span></tt>-style String Formatting</a></li>
</ul>
</li>
<li><a class="reference internal" href="#binary-sequence-types-bytes-bytearray-memoryview">4.8. Binary Sequence Types &#8212; <tt class="docutils literal"><span class="pre">bytes</span></tt>, <tt class="docutils literal"><span class="pre">bytearray</span></tt>, <tt class="docutils literal"><span class="pre">memoryview</span></tt></a><ul>
<li><a class="reference internal" href="#bytes">4.8.1. Bytes</a></li>
<li><a class="reference internal" href="#bytearray-objects">4.8.2. Bytearray Objects</a></li>
<li><a class="reference internal" href="#bytes-and-bytearray-operations">4.8.3. Bytes and Bytearray Operations</a></li>
<li><a class="reference internal" href="#memory-views">4.8.4. Memory Views</a></li>
</ul>
</li>
<li><a class="reference internal" href="#set-types-set-frozenset">4.9. Set Types &#8212; <tt class="docutils literal"><span class="pre">set</span></tt>, <tt class="docutils literal"><span class="pre">frozenset</span></tt></a></li>
<li><a class="reference internal" href="#mapping-types-dict">4.10. Mapping Types &#8212; <tt class="docutils literal"><span class="pre">dict</span></tt></a><ul>
<li><a class="reference internal" href="#dictionary-view-objects">4.10.1. Dictionary view objects</a></li>
</ul>
</li>
<li><a class="reference internal" href="#context-manager-types">4.11. Context Manager Types</a></li>
<li><a class="reference internal" href="#other-built-in-types">4.12. Other Built-in Types</a><ul>
<li><a class="reference internal" href="#modules">4.12.1. Modules</a></li>
<li><a class="reference internal" href="#classes-and-class-instances">4.12.2. Classes and Class Instances</a></li>
<li><a class="reference internal" href="#functions">4.12.3. Functions</a></li>
<li><a class="reference internal" href="#methods">4.12.4. Methods</a></li>
<li><a class="reference internal" href="#code-objects">4.12.5. Code Objects</a></li>
<li><a class="reference internal" href="#type-objects">4.12.6. Type Objects</a></li>
<li><a class="reference internal" href="#the-null-object">4.12.7. The Null Object</a></li>
<li><a class="reference internal" href="#the-ellipsis-object">4.12.8. The Ellipsis Object</a></li>
<li><a class="reference internal" href="#the-notimplemented-object">4.12.9. The NotImplemented Object</a></li>
<li><a class="reference internal" href="#boolean-values">4.12.10. Boolean Values</a></li>
<li><a class="reference internal" href="#internal-objects">4.12.11. Internal Objects</a></li>
</ul>
</li>
<li><a class="reference internal" href="#special-attributes">4.13. Special Attributes</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="constants.html"
                        title="previous chapter">3. Built-in Constants</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="exceptions.html"
                        title="next chapter">5. Built-in Exceptions</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/library/stdtypes.txt"
         rel="nofollow">Show Source</a></li>
</ul>

<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="exceptions.html" title="5. Built-in Exceptions"
             >next</a> |</li>
        <li class="right" >
          <a href="constants.html" title="3. Built-in Constants"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="http://www.python.org/">Python</a> &raquo;</li>
        <li><a href="../index.html">3.3.0 Documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2012, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.  
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Sep 29, 2012.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0.7.
    </div>

  </body>
</html>