2649 lines
286 KiB
HTML
2649 lines
286 KiB
HTML
<!DOCTYPE html>
|
||
|
||
<html lang="en" data-content_root="../">
|
||
<head>
|
||
<meta charset="utf-8" />
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||
<meta property="og:title" content="6. Expressions" />
|
||
<meta property="og:type" content="website" />
|
||
<meta property="og:url" content="https://docs.python.org/3/reference/expressions.html" />
|
||
<meta property="og:site_name" content="Python documentation" />
|
||
<meta property="og:description" content="This chapter explains the meaning of the elements of expressions in Python. Syntax Notes: In this and the following chapters, grammar notation will be used to describe syntax, not lexical analysis...." />
|
||
<meta property="og:image" content="_static/og-image.png" />
|
||
<meta property="og:image:alt" content="Python documentation" />
|
||
<meta name="description" content="This chapter explains the meaning of the elements of expressions in Python. Syntax Notes: In this and the following chapters, grammar notation will be used to describe syntax, not lexical analysis...." />
|
||
<meta name="theme-color" content="#3776ab">
|
||
<meta property="og:image:width" content="200">
|
||
<meta property="og:image:height" content="200">
|
||
|
||
<title>6. Expressions — Python 3.15.0 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
|
||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||
<link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" />
|
||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=48df1187" />
|
||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=0fc419ee" />
|
||
|
||
<script src="../_static/documentation_options.js?v=0fe728b1"></script>
|
||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||
|
||
<script src="../_static/sidebar.js"></script>
|
||
|
||
<link rel="search" type="application/opensearchdescription+xml"
|
||
title="Search within Python 3.15.0 documentation"
|
||
href="../_static/opensearch.xml"/>
|
||
<link rel="author" title="About these documents" href="../about.html" />
|
||
<link rel="index" title="Index" href="../genindex.html" />
|
||
<link rel="search" title="Search" href="../search.html" />
|
||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||
<link rel="next" title="7. Simple statements" href="simple_stmts.html" />
|
||
<link rel="prev" title="5. The import system" href="import.html" />
|
||
|
||
|
||
<link rel="canonical" href="https://docs.python.org/3/reference/expressions.html">
|
||
|
||
|
||
|
||
|
||
<style>
|
||
@media only screen {
|
||
table.full-width-table {
|
||
width: 100%;
|
||
}
|
||
}
|
||
</style>
|
||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg">
|
||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||
<meta name="readthedocs-addons-api-version" content="1">
|
||
|
||
</head>
|
||
<body>
|
||
<div class="mobile-nav">
|
||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu">
|
||
<nav class="nav-content" role="navigation">
|
||
<label for="menuToggler" class="toggler__label">
|
||
<span></span>
|
||
</label>
|
||
<span class="nav-items-wrapper">
|
||
<a href="https://www.python.org/" class="nav-logo">
|
||
<img src="../_static/py.svg" alt="Python logo">
|
||
</a>
|
||
<span class="version_switcher_placeholder"></span>
|
||
<form role="search" class="search" action="../search.html" method="get">
|
||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||
<path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
|
||
</svg>
|
||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q">
|
||
<input type="submit" value="Go">
|
||
</form>
|
||
</span>
|
||
</nav>
|
||
<div class="menu-wrapper">
|
||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||
<div class="language_switcher_placeholder"></div>
|
||
|
||
<label class="theme-selector-label">
|
||
Theme
|
||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||
<option value="auto" selected>Auto</option>
|
||
<option value="light">Light</option>
|
||
<option value="dark">Dark</option>
|
||
</select>
|
||
</label>
|
||
<div>
|
||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||
<ul>
|
||
<li><a class="reference internal" href="#">6. Expressions</a><ul>
|
||
<li><a class="reference internal" href="#arithmetic-conversions">6.1. Arithmetic conversions</a></li>
|
||
<li><a class="reference internal" href="#atoms">6.2. Atoms</a><ul>
|
||
<li><a class="reference internal" href="#built-in-constants">6.2.1. Built-in constants</a></li>
|
||
<li><a class="reference internal" href="#atom-identifiers">6.2.2. Identifiers (Names)</a><ul>
|
||
<li><a class="reference internal" href="#index-5">6.2.2.1. Private name mangling</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#literals">6.2.3. Literals</a><ul>
|
||
<li><a class="reference internal" href="#literals-and-object-identity">6.2.3.1. Literals and object identity</a></li>
|
||
<li><a class="reference internal" href="#string-literal-concatenation">6.2.3.2. String literal concatenation</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#parenthesized-groups">6.2.4. Parenthesized groups</a></li>
|
||
<li><a class="reference internal" href="#container-displays">6.2.5. Container displays</a><ul>
|
||
<li><a class="reference internal" href="#list-displays">6.2.5.1. List displays</a></li>
|
||
<li><a class="reference internal" href="#set-displays">6.2.5.2. Set displays</a></li>
|
||
<li><a class="reference internal" href="#tuple-displays">6.2.5.3. Tuple displays</a></li>
|
||
<li><a class="reference internal" href="#dictionary-displays">6.2.5.4. Dictionary displays</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#comprehensions">6.2.6. Comprehensions</a><ul>
|
||
<li><a class="reference internal" href="#filtering-in-comprehensions">6.2.6.1. Filtering in comprehensions</a></li>
|
||
<li><a class="reference internal" href="#complex-comprehensions">6.2.6.2. Complex comprehensions</a></li>
|
||
<li><a class="reference internal" href="#unpacking-in-comprehensions">6.2.6.3. Unpacking in comprehensions</a></li>
|
||
<li><a class="reference internal" href="#asynchronous-comprehensions">6.2.6.4. Asynchronous comprehensions</a></li>
|
||
<li><a class="reference internal" href="#formal-grammar-for-comprehensions">6.2.6.5. Formal grammar for comprehensions</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#generator-expressions">6.2.7. Generator expressions</a></li>
|
||
<li><a class="reference internal" href="#yield-expressions">6.2.8. Yield expressions</a><ul>
|
||
<li><a class="reference internal" href="#generator-iterator-methods">6.2.8.1. Generator-iterator methods</a></li>
|
||
<li><a class="reference internal" href="#examples">6.2.8.2. Examples</a></li>
|
||
<li><a class="reference internal" href="#asynchronous-generator-functions">6.2.8.3. Asynchronous generator functions</a></li>
|
||
<li><a class="reference internal" href="#asynchronous-generator-iterator-methods">6.2.8.4. Asynchronous generator-iterator methods</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#primaries">6.3. Primaries</a><ul>
|
||
<li><a class="reference internal" href="#attribute-references">6.3.1. Attribute references</a></li>
|
||
<li><a class="reference internal" href="#subscriptions-and-slicings">6.3.2. Subscriptions and slicings</a><ul>
|
||
<li><a class="reference internal" href="#slicings">6.3.2.1. Slicings</a></li>
|
||
<li><a class="reference internal" href="#comma-separated-subscripts">6.3.2.2. Comma-separated subscripts</a></li>
|
||
<li><a class="reference internal" href="#starred-subscriptions">6.3.2.3. “Starred” subscriptions</a></li>
|
||
<li><a class="reference internal" href="#formal-subscription-grammar">6.3.2.4. Formal subscription grammar</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#calls">6.3.3. Calls</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#await-expression">6.4. Await expression</a></li>
|
||
<li><a class="reference internal" href="#the-power-operator">6.5. The power operator</a></li>
|
||
<li><a class="reference internal" href="#unary-arithmetic-and-bitwise-operations">6.6. Unary arithmetic and bitwise operations</a></li>
|
||
<li><a class="reference internal" href="#binary-arithmetic-operations">6.7. Binary arithmetic operations</a></li>
|
||
<li><a class="reference internal" href="#shifting-operations">6.8. Shifting operations</a></li>
|
||
<li><a class="reference internal" href="#binary-bitwise-operations">6.9. Binary bitwise operations</a></li>
|
||
<li><a class="reference internal" href="#comparisons">6.10. Comparisons</a><ul>
|
||
<li><a class="reference internal" href="#value-comparisons">6.10.1. Value comparisons</a></li>
|
||
<li><a class="reference internal" href="#membership-test-operations">6.10.2. Membership test operations</a></li>
|
||
<li><a class="reference internal" href="#is-not">6.10.3. Identity comparisons</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#boolean-operations">6.11. Boolean operations</a></li>
|
||
<li><a class="reference internal" href="#assignment-expressions">6.12. Assignment expressions</a></li>
|
||
<li><a class="reference internal" href="#conditional-expressions">6.13. Conditional expressions</a></li>
|
||
<li><a class="reference internal" href="#lambda">6.14. Lambdas</a></li>
|
||
<li><a class="reference internal" href="#expression-lists">6.15. Expression lists</a><ul>
|
||
<li><a class="reference internal" href="#index-98">6.15.1. Iterable unpacking</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#evaluation-order">6.16. Evaluation order</a></li>
|
||
<li><a class="reference internal" href="#operator-precedence">6.17. Operator precedence</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
|
||
</div>
|
||
<div>
|
||
<h4>Previous topic</h4>
|
||
<p class="topless"><a href="import.html"
|
||
title="previous chapter"><span class="section-number">5. </span>The import system</a></p>
|
||
</div>
|
||
<div>
|
||
<h4>Next topic</h4>
|
||
<p class="topless"><a href="simple_stmts.html"
|
||
title="next chapter"><span class="section-number">7. </span>Simple statements</a></p>
|
||
</div>
|
||
<script>
|
||
document.addEventListener('DOMContentLoaded', () => {
|
||
const title = document.querySelector('meta[property="og:title"]').content;
|
||
const elements = document.querySelectorAll('.improvepage');
|
||
const pageurl = window.location.href.split('?')[0];
|
||
elements.forEach(element => {
|
||
const url = new URL(element.href.split('?')[0].replace("-nojs", ""));
|
||
url.searchParams.set('pagetitle', title);
|
||
url.searchParams.set('pageurl', pageurl);
|
||
url.searchParams.set('pagesource', "reference/expressions.rst");
|
||
element.href = url.toString();
|
||
});
|
||
});
|
||
</script>
|
||
<div role="note" aria-label="source link">
|
||
<h3>This page</h3>
|
||
<ul class="this-page-menu">
|
||
<li><a href="../bugs.html">Report a bug</a></li>
|
||
<li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>
|
||
<li>
|
||
<a href="https://github.com/python/cpython/blob/3.15/Doc/reference/expressions.rst?plain=1"
|
||
rel="nofollow">Show source
|
||
</a>
|
||
</li>
|
||
|
||
</ul>
|
||
</div>
|
||
</nav>
|
||
</div>
|
||
</div>
|
||
|
||
|
||
<div class="related" role="navigation" aria-label="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="simple_stmts.html" title="7. Simple statements"
|
||
accesskey="N">next</a> |</li>
|
||
<li class="right" >
|
||
<a href="import.html" title="5. The import system"
|
||
accesskey="P">previous</a> |</li>
|
||
|
||
<li class="root-icon"><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>
|
||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||
<li class="switchers">
|
||
<div class="language_switcher_placeholder"></div>
|
||
<div class="version_switcher_placeholder"></div>
|
||
</li>
|
||
<li>
|
||
|
||
</li>
|
||
<li id="cpython-language-and-version">
|
||
<a href="../index.html">3.15.0 Documentation</a> »
|
||
</li>
|
||
|
||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> »</li>
|
||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">6. </span>Expressions</a></li>
|
||
<li class="right">
|
||
|
||
|
||
<div class="inline-search" role="search">
|
||
<form class="inline-search" action="../search.html" method="get">
|
||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">
|
||
<input type="submit" value="Go">
|
||
</form>
|
||
</div>
|
||
|
|
||
</li>
|
||
<li class="right">
|
||
<label class="theme-selector-label">
|
||
Theme
|
||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||
<option value="auto" selected>Auto</option>
|
||
<option value="light">Light</option>
|
||
<option value="dark">Dark</option>
|
||
</select>
|
||
</label> |</li>
|
||
|
||
</ul>
|
||
</div>
|
||
|
||
<div class="document">
|
||
<div class="documentwrapper">
|
||
<div class="bodywrapper">
|
||
<div class="body" role="main">
|
||
|
||
<section id="expressions">
|
||
<span id="id1"></span><h1><span class="section-number">6. </span>Expressions<a class="headerlink" href="#expressions" title="Link to this heading">¶</a></h1>
|
||
<p id="index-0">This chapter explains the meaning of the elements of expressions in Python.</p>
|
||
<p><strong>Syntax Notes:</strong> In this and the following chapters,
|
||
<a class="reference internal" href="introduction.html#notation"><span class="std std-ref">grammar notation</span></a> will be used to describe syntax,
|
||
not lexical analysis.</p>
|
||
<p>When (one alternative of) a syntax rule has the form:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-name">name</strong>: othername
|
||
</pre>
|
||
<p>and no semantics are given, the semantics of this form of <code class="docutils literal notranslate"><span class="pre">name</span></code> are the same
|
||
as for <code class="docutils literal notranslate"><span class="pre">othername</span></code>.</p>
|
||
<section id="arithmetic-conversions">
|
||
<span id="conversions"></span><h2><span class="section-number">6.1. </span>Arithmetic conversions<a class="headerlink" href="#arithmetic-conversions" title="Link to this heading">¶</a></h2>
|
||
<p id="index-1">When a description of an arithmetic operator below uses the phrase “the numeric
|
||
arguments are converted to a common real type”, this means that the operator
|
||
implementation for built-in numeric types works as described in the
|
||
<a class="reference internal" href="../builtins/stdtypes.html#stdtypes-mixed-arithmetic"><span class="std std-ref">Numeric Types</span></a> section of the standard
|
||
library documentation.</p>
|
||
<p>Some additional rules apply for certain operators and non-numeric operands
|
||
(for example, a string as a left argument to the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator).
|
||
Extensions must define their own conversion behavior.</p>
|
||
</section>
|
||
<section id="atoms">
|
||
<span id="id2"></span><h2><span class="section-number">6.2. </span>Atoms<a class="headerlink" href="#atoms" title="Link to this heading">¶</a></h2>
|
||
<p id="index-2">Atoms are the most basic elements of expressions.
|
||
The simplest atoms are <a class="reference internal" href="#atom-singletons"><span class="std std-ref">builtin constants</span></a>,
|
||
<a class="reference internal" href="lexical_analysis.html#identifiers"><span class="std std-ref">names</span></a> and <a class="reference internal" href="#atom-literals"><span class="std std-ref">literals</span></a>.
|
||
More complex atoms are enclosed in paired delimiters:</p>
|
||
<ul class="simple">
|
||
<li><p><code class="docutils literal notranslate"><span class="pre">()</span></code> (parentheses): <a class="reference internal" href="#parenthesized"><span class="std std-ref">groups</span></a>,
|
||
<a class="reference internal" href="#tuple-display"><span class="std std-ref">tuple displays</span></a>,
|
||
<a class="reference internal" href="#yieldexpr"><span class="std std-ref">yield atoms</span></a>, and
|
||
<a class="reference internal" href="#genexpr"><span class="std std-ref">generator expressions</span></a>;</p></li>
|
||
<li><p><code class="docutils literal notranslate"><span class="pre">[]</span></code> (square brackets): <a class="reference internal" href="#lists"><span class="std std-ref">list displays</span></a>;</p></li>
|
||
<li><p><code class="docutils literal notranslate"><span class="pre">{}</span></code> (curly braces): <a class="reference internal" href="#dict"><span class="std std-ref">dictionary</span></a> and <a class="reference internal" href="#set"><span class="std std-ref">set</span></a> displays.</p></li>
|
||
</ul>
|
||
<p>Formally, the syntax for atoms is:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-atom">atom</strong>:
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-builtin_constant"><code class="xref docutils literal notranslate"><span class="pre">builtin_constant</span></code></a>
|
||
| <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-literal"><code class="xref docutils literal notranslate"><span class="pre">literal</span></code></a>
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-parenthesized_enclosure"><code class="xref docutils literal notranslate"><span class="pre">parenthesized_enclosure</span></code></a>
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-bracketed_enclosure"><code class="xref docutils literal notranslate"><span class="pre">bracketed_enclosure</span></code></a>
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-braced_enclosure"><code class="xref docutils literal notranslate"><span class="pre">braced_enclosure</span></code></a>
|
||
<strong id="grammar-token-python-grammar-parenthesized_enclosure">parenthesized_enclosure</strong>:
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-group"><code class="xref docutils literal notranslate"><span class="pre">group</span></code></a>
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-tuple"><code class="xref docutils literal notranslate"><span class="pre">tuple</span></code></a>
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-yield_atom"><code class="xref docutils literal notranslate"><span class="pre">yield_atom</span></code></a>
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-generator_expression"><code class="xref docutils literal notranslate"><span class="pre">generator_expression</span></code></a>
|
||
<strong id="grammar-token-python-grammar-bracketed_enclosure">bracketed_enclosure</strong>:
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-listcomp"><code class="xref docutils literal notranslate"><span class="pre">listcomp</span></code></a>
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-list"><code class="xref docutils literal notranslate"><span class="pre">list</span></code></a>
|
||
<strong id="grammar-token-python-grammar-braced_enclosure">braced_enclosure</strong>:
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-dictcomp"><code class="xref docutils literal notranslate"><span class="pre">dictcomp</span></code></a>
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-dict"><code class="xref docutils literal notranslate"><span class="pre">dict</span></code></a>
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-setcomp"><code class="xref docutils literal notranslate"><span class="pre">setcomp</span></code></a>
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-set"><code class="xref docutils literal notranslate"><span class="pre">set</span></code></a>
|
||
</pre>
|
||
<section id="built-in-constants">
|
||
<span id="atom-singletons"></span><h3><span class="section-number">6.2.1. </span>Built-in constants<a class="headerlink" href="#built-in-constants" title="Link to this heading">¶</a></h3>
|
||
<p>The keywords <code class="docutils literal notranslate"><span class="pre">True</span></code>, <code class="docutils literal notranslate"><span class="pre">False</span></code>, and <code class="docutils literal notranslate"><span class="pre">None</span></code> name
|
||
<a class="reference internal" href="../builtins/constants.html#built-in-consts"><span class="std std-ref">built-in constants</span></a>.
|
||
The token <code class="docutils literal notranslate"><span class="pre">...</span></code> names the <a class="reference internal" href="../builtins/constants.html#Ellipsis" title="Ellipsis"><code class="xref py py-data docutils literal notranslate"><span class="pre">Ellipsis</span></code></a> constant.</p>
|
||
<p>Evaluation of these atoms yields the corresponding value.</p>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">Note</p>
|
||
<p>Several more built-in constants are available as global variables,
|
||
but only the ones mentioned here are <a class="reference internal" href="lexical_analysis.html#keywords"><span class="std std-ref">keywords</span></a>.
|
||
In particular, these names cannot be reassigned or used as attributes:</p>
|
||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kc">False</span> <span class="o">=</span> <span class="mi">123</span>
|
||
File <span class="nb">"<input>"</span>, line <span class="m">1</span>
|
||
<span class="gr"> False = 123</span>
|
||
<span class="gr"> ^^^^^</span>
|
||
<span class="gr">SyntaxError</span>: <span class="n">cannot assign to False</span>
|
||
</pre></div>
|
||
</div>
|
||
</div>
|
||
<p>Formally, the syntax for built-in constants is:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-builtin_constant">builtin_constant</strong>: <span class="sx">'True'</span> | <span class="sx">'False'</span> | <span class="sx">'None'</span> | <span class="sx">'...'</span>
|
||
</pre>
|
||
</section>
|
||
<section id="atom-identifiers">
|
||
<span id="identifiers-names"></span><h3><span class="section-number">6.2.2. </span>Identifiers (Names)<a class="headerlink" href="#atom-identifiers" title="Link to this heading">¶</a></h3>
|
||
<p id="index-3">An identifier occurring as an atom is a name. See section <a class="reference internal" href="lexical_analysis.html#identifiers"><span class="std std-ref">Names (identifiers and keywords)</span></a>
|
||
for lexical definition and section <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">Naming and binding</span></a> for documentation of naming and
|
||
binding.</p>
|
||
<p id="index-4">When the name is bound to an object, evaluation of the atom yields that object.
|
||
When a name is not bound, an attempt to evaluate it raises a <a class="reference internal" href="../builtins/exceptions.html#NameError" title="NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a>
|
||
exception.</p>
|
||
<section id="index-5">
|
||
<span id="private-name-mangling"></span><span id="id3"></span><h4><span class="section-number">6.2.2.1. </span>Private name mangling<a class="headerlink" href="#index-5" title="Link to this heading">¶</a></h4>
|
||
<p>When an identifier that textually occurs in a class definition begins with two
|
||
or more underscore characters and does not end in two or more underscores, it
|
||
is considered a <em class="dfn">private name</em> of that class.</p>
|
||
<div class="admonition seealso">
|
||
<p class="admonition-title">See also</p>
|
||
<p>The <a class="reference internal" href="compound_stmts.html#class"><span class="std std-ref">class specifications</span></a>.</p>
|
||
</div>
|
||
<p>More precisely, private names are transformed to a longer form before code is
|
||
generated for them. If the transformed name is longer than 255 characters,
|
||
implementation-defined truncation may happen.</p>
|
||
<p>The transformation is independent of the syntactical context in which the
|
||
identifier is used but only the following private identifiers are mangled:</p>
|
||
<ul>
|
||
<li><p>Any name used as the name of a variable that is assigned or read or any
|
||
name of an attribute being accessed.</p>
|
||
<p>The <a class="reference internal" href="../builtins/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> attribute of nested functions, classes, and
|
||
type aliases is however not mangled.</p>
|
||
</li>
|
||
<li><p>The name of imported modules, e.g., <code class="docutils literal notranslate"><span class="pre">__spam</span></code> in <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">__spam</span></code>.
|
||
If the module is part of a package (i.e., its name contains a dot),
|
||
the name is <em>not</em> mangled, e.g., the <code class="docutils literal notranslate"><span class="pre">__foo</span></code> in <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">__foo.bar</span></code>
|
||
is not mangled.</p></li>
|
||
<li><p>The name of an imported member, e.g., <code class="docutils literal notranslate"><span class="pre">__f</span></code> in <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">spam</span> <span class="pre">import</span> <span class="pre">__f</span></code>.</p></li>
|
||
</ul>
|
||
<p>The transformation rule is defined as follows:</p>
|
||
<ul class="simple">
|
||
<li><p>The class name, with leading underscores removed and a single leading
|
||
underscore inserted, is inserted in front of the identifier, e.g., the
|
||
identifier <code class="docutils literal notranslate"><span class="pre">__spam</span></code> occurring in a class named <code class="docutils literal notranslate"><span class="pre">Foo</span></code>, <code class="docutils literal notranslate"><span class="pre">_Foo</span></code> or
|
||
<code class="docutils literal notranslate"><span class="pre">__Foo</span></code> is transformed to <code class="docutils literal notranslate"><span class="pre">_Foo__spam</span></code>.</p></li>
|
||
<li><p>If the class name consists only of underscores, the transformation is the
|
||
identity, e.g., the identifier <code class="docutils literal notranslate"><span class="pre">__spam</span></code> occurring in a class named <code class="docutils literal notranslate"><span class="pre">_</span></code>
|
||
or <code class="docutils literal notranslate"><span class="pre">__</span></code> is left as is.</p></li>
|
||
</ul>
|
||
</section>
|
||
</section>
|
||
<section id="literals">
|
||
<span id="atom-literals"></span><h3><span class="section-number">6.2.3. </span>Literals<a class="headerlink" href="#literals" title="Link to this heading">¶</a></h3>
|
||
<p id="index-6">A <em class="dfn">literal</em> is a textual representation of a value.
|
||
Python supports numeric, string and bytes literals.
|
||
<a class="reference internal" href="lexical_analysis.html#f-strings"><span class="std std-ref">Format strings</span></a> and <a class="reference internal" href="lexical_analysis.html#t-strings"><span class="std std-ref">template strings</span></a>
|
||
are treated as string literals.</p>
|
||
<p>Numeric literals consist of a single <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-NUMBER"><code class="xref std std-token docutils literal notranslate"><span class="pre">NUMBER</span></code></a>
|
||
token, which names an integer, floating-point number, or an imaginary number.
|
||
See the <a class="reference internal" href="lexical_analysis.html#numbers"><span class="std std-ref">Numeric literals</span></a> section in Lexical analysis documentation for details.</p>
|
||
<p>String and bytes literals may consist of several tokens.
|
||
See section <a class="reference internal" href="#string-concatenation"><span class="std std-ref">String literal concatenation</span></a> for details.</p>
|
||
<p>Note that negative and complex numbers, like <code class="docutils literal notranslate"><span class="pre">-3</span></code> or <code class="docutils literal notranslate"><span class="pre">3+4.2j</span></code>,
|
||
are syntactically not literals, but <a class="reference internal" href="#unary"><span class="std std-ref">unary</span></a> or
|
||
<a class="reference internal" href="#binary"><span class="std std-ref">binary</span></a> arithmetic operations involving the <code class="docutils literal notranslate"><span class="pre">-</span></code> or <code class="docutils literal notranslate"><span class="pre">+</span></code>
|
||
operator.</p>
|
||
<p>Evaluation of a literal yields an object of the given type
|
||
(<a class="reference internal" href="../builtins/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <a class="reference internal" href="../builtins/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, <a class="reference internal" href="../builtins/functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a>, <a class="reference internal" href="../builtins/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>,
|
||
<a class="reference internal" href="../builtins/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>, or <a class="reference internal" href="../library/string.templatelib.html#string.templatelib.Template" title="string.templatelib.Template"><code class="xref py py-class docutils literal notranslate"><span class="pre">Template</span></code></a>) with the given value.
|
||
The value may be approximated in the case of floating-point
|
||
and imaginary literals.</p>
|
||
<p>The formal grammar for literals is:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-literal">literal</strong>: <a class="reference internal" href="#grammar-token-python-grammar-strings"><code class="xref docutils literal notranslate"><span class="pre">strings</span></code></a> | <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-NUMBER"><code class="xref docutils literal notranslate"><span class="pre">NUMBER</span></code></a>
|
||
</pre>
|
||
<section id="literals-and-object-identity">
|
||
<span id="index-7"></span><span id="literals-identity"></span><h4><span class="section-number">6.2.3.1. </span>Literals and object identity<a class="headerlink" href="#literals-and-object-identity" title="Link to this heading">¶</a></h4>
|
||
<p>All literals correspond to immutable data types, and hence the object’s identity
|
||
is less important than its value. Multiple evaluations of literals with the
|
||
same value (either the same occurrence in the program text or a different
|
||
occurrence) may obtain the same object or a different object with the same
|
||
value.</p>
|
||
<div class="admonition-cpython-implementation-detail admonition">
|
||
<p class="admonition-title">CPython implementation detail</p>
|
||
<p>For example, in CPython, <em>small</em> integers with the same value evaluate
|
||
to the same object:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="mi">7</span>
|
||
<span class="gp">>>> </span><span class="n">y</span> <span class="o">=</span> <span class="mi">7</span>
|
||
<span class="gp">>>> </span><span class="n">x</span> <span class="ow">is</span> <span class="n">y</span>
|
||
<span class="go">True</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>However, large integers evaluate to different objects:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="mi">123456789</span>
|
||
<span class="gp">>>> </span><span class="n">y</span> <span class="o">=</span> <span class="mi">123456789</span>
|
||
<span class="gp">>>> </span><span class="n">x</span> <span class="ow">is</span> <span class="n">y</span>
|
||
<span class="go">False</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>This behavior may change in future versions of CPython.
|
||
In particular, the boundary between “small” and “large” integers has
|
||
already changed in the past.</p>
|
||
<p>CPython will emit a <a class="reference internal" href="../builtins/exceptions.html#SyntaxWarning" title="SyntaxWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxWarning</span></code></a> when you compare literals
|
||
using <code class="docutils literal notranslate"><span class="pre">is</span></code>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="mi">7</span>
|
||
<span class="gp">>>> </span><span class="n">x</span> <span class="ow">is</span> <span class="mi">7</span>
|
||
<span class="go"><input>:1: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?</span>
|
||
<span class="go">True</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>See <a class="reference internal" href="../faq/programming.html#faq-identity-with-is"><span class="std std-ref">When can I rely on identity tests with the is operator?</span></a> for more information.</p>
|
||
</div>
|
||
<p><a class="reference internal" href="lexical_analysis.html#t-strings"><span class="std std-ref">Template strings</span></a> are immutable but may reference mutable
|
||
objects as <a class="reference internal" href="../library/string.templatelib.html#string.templatelib.Interpolation" title="string.templatelib.Interpolation"><code class="xref py py-class docutils literal notranslate"><span class="pre">Interpolation</span></code></a> values.
|
||
For the purposes of this section, two t-strings have the “same value” if
|
||
both their structure and the <em>identity</em> of the values match.</p>
|
||
<div class="impl-detail compound">
|
||
<p><strong>CPython implementation detail:</strong> Currently, each evaluation of a template string results in
|
||
a different object.</p>
|
||
</div>
|
||
</section>
|
||
<section id="string-literal-concatenation">
|
||
<span id="string-concatenation"></span><h4><span class="section-number">6.2.3.2. </span>String literal concatenation<a class="headerlink" href="#string-literal-concatenation" title="Link to this heading">¶</a></h4>
|
||
<p>Multiple adjacent string or bytes literals, possibly
|
||
using different quoting conventions, are allowed, and their meaning is the same
|
||
as their concatenation:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="s2">"hello"</span> <span class="s1">'world'</span>
|
||
<span class="go">"helloworld"</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>This feature is defined at the syntactical level, so it only works with literals.
|
||
To concatenate string expressions at run time, the ‘+’ operator may be used:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">greeting</span> <span class="o">=</span> <span class="s2">"Hello"</span>
|
||
<span class="gp">>>> </span><span class="n">space</span> <span class="o">=</span> <span class="s2">" "</span>
|
||
<span class="gp">>>> </span><span class="n">name</span> <span class="o">=</span> <span class="s2">"Blaise"</span>
|
||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">greeting</span> <span class="o">+</span> <span class="n">space</span> <span class="o">+</span> <span class="n">name</span><span class="p">)</span> <span class="c1"># not: print(greeting space name)</span>
|
||
<span class="go">Hello Blaise</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Literal concatenation can freely mix raw strings, triple-quoted strings,
|
||
and formatted string literals.
|
||
For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="s2">"Hello"</span> <span class="sa">r</span><span class="s1">', '</span> <span class="sa">f</span><span class="s2">"</span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s2">!"</span>
|
||
<span class="go">"Hello, Blaise!"</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>This feature can be used to reduce the number of backslashes
|
||
needed, to split long strings conveniently across long lines, or even to add
|
||
comments to parts of strings. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s2">"[A-Za-z_]"</span> <span class="c1"># letter or underscore</span>
|
||
<span class="s2">"[A-Za-z0-9_]*"</span> <span class="c1"># letter, digit or underscore</span>
|
||
<span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>However, bytes literals may only be combined with other byte literals;
|
||
not with string literals of any kind.
|
||
Also, template string literals may only be combined with other template
|
||
string literals:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="sa">t</span><span class="s2">"Hello"</span> <span class="sa">t</span><span class="s2">"</span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s2">!"</span>
|
||
<span class="go">Template(strings=('Hello', '!'), interpolations=(...))</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Formally:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-strings">strings</strong>: (<a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-STRING"><code class="xref docutils literal notranslate"><span class="pre">STRING</span></code></a> | <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-fstring"><code class="xref docutils literal notranslate"><span class="pre">fstring</span></code></a>)+ | <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-tstring"><code class="xref docutils literal notranslate"><span class="pre">tstring</span></code></a>+
|
||
</pre>
|
||
</section>
|
||
</section>
|
||
<section id="parenthesized-groups">
|
||
<span id="parenthesized"></span><span id="parenthesized-forms"></span><span id="index-8"></span><h3><span class="section-number">6.2.4. </span>Parenthesized groups<a class="headerlink" href="#parenthesized-groups" title="Link to this heading">¶</a></h3>
|
||
<p>A <em class="dfn">parenthesized group</em> is an expression enclosed in parentheses.
|
||
The group evaluates to the same value as the expression inside.</p>
|
||
<p>Groups are used to override or clarify
|
||
<a class="reference internal" href="#operator-precedence"><span class="std std-ref">operator precedence</span></a>,
|
||
in the same way as in math notation.
|
||
For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="mi">3</span> <span class="o"><<</span> <span class="mi">2</span> <span class="o">|</span> <span class="mi">4</span>
|
||
<span class="go">12</span>
|
||
<span class="gp">>>> </span><span class="mi">3</span> <span class="o"><<</span> <span class="p">(</span><span class="mi">2</span> <span class="o">|</span> <span class="mi">4</span><span class="p">)</span> <span class="c1"># Override precedence of the | (bitwise OR)</span>
|
||
<span class="go">192</span>
|
||
<span class="gp">>>> </span><span class="p">(</span><span class="mi">3</span> <span class="o"><<</span> <span class="mi">2</span><span class="p">)</span> <span class="o">|</span> <span class="mi">4</span> <span class="c1"># Same as without parentheses (but more clear)</span>
|
||
<span class="go">12</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Note that not everything in parentheses is a <em>group</em>.
|
||
Specifically, a parenthesized group must include exactly one expression,
|
||
and cannot end with a comma.
|
||
See <a class="reference internal" href="#tuple-display"><span class="std std-ref">tuple displays</span></a> and
|
||
<a class="reference internal" href="#genexpr"><span class="std std-ref">generator expressions</span></a> for other parenthesized forms.</p>
|
||
<p>Formally, the syntax for groups is:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-group">group</strong>: <span class="sx">'('</span> <a class="reference internal" href="#grammar-token-python-grammar-assignment_expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> <span class="sx">')'</span>
|
||
</pre>
|
||
</section>
|
||
<section id="container-displays">
|
||
<span id="displays"></span><span id="displays-for-lists-sets-and-dictionaries"></span><h3><span class="section-number">6.2.5. </span>Container displays<a class="headerlink" href="#container-displays" title="Link to this heading">¶</a></h3>
|
||
<p id="index-9">For constructing builtin containers (lists, sets, tuples or dictionaries),
|
||
Python provides special syntax called <em class="dfn">displays</em>.
|
||
There are subtle differences between the four kinds of displays,
|
||
detailed in the following sections.
|
||
All displays, however, consist of comma-separated items enclosed in paired
|
||
delimiters.</p>
|
||
<p>For example, a <em>list display</em> is a series of expressions enclosed in
|
||
square brackets:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">[</span><span class="s2">"one"</span><span class="p">,</span> <span class="s2">"two"</span><span class="p">,</span> <span class="s2">"three"</span><span class="p">]</span>
|
||
<span class="go">['one', 'two', 'three']</span>
|
||
<span class="gp">>>> </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="mi">2</span> <span class="o">+</span> <span class="mi">3</span><span class="p">]</span>
|
||
<span class="go">[3, 5]</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>In list, tuple and dictionary (but not set) displays, the series may be empty:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">[]</span> <span class="c1"># empty list</span>
|
||
<span class="go">[]</span>
|
||
<span class="gp">>>> </span><span class="p">()</span> <span class="c1"># empty tuple</span>
|
||
<span class="go">()</span>
|
||
<span class="gp">>>> </span><span class="p">{}</span> <span class="c1"># empty dictionary</span>
|
||
<span class="go">{}</span>
|
||
</pre></div>
|
||
</div>
|
||
<p id="index-10">If the series is not empty, the items may be followed by an additional comma,
|
||
which has no effect:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">[</span><span class="s2">"one"</span><span class="p">,</span> <span class="s2">"two"</span><span class="p">,</span> <span class="s2">"three"</span><span class="p">,]</span> <span class="c1"># note comma after "three"</span>
|
||
<span class="go">['one', 'two', 'three']</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">Note</p>
|
||
<p>The trailing comma is often used for displays that span multiple lines
|
||
(using <a class="reference internal" href="lexical_analysis.html#implicit-joining"><span class="std std-ref">implicit line joining</span></a>),
|
||
so when a future programmer adds a new entry at the end, they do not
|
||
need to modify an existing line:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">[</span>
|
||
<span class="gp">... </span> <span class="s1">'one'</span><span class="p">,</span>
|
||
<span class="gp">... </span> <span class="s1">'two'</span><span class="p">,</span>
|
||
<span class="gp">... </span> <span class="s1">'three'</span><span class="p">,</span>
|
||
<span class="gp">... </span><span class="p">]</span>
|
||
<span class="go">['one', 'two', 'three']</span>
|
||
</pre></div>
|
||
</div>
|
||
</div>
|
||
<p>At runtime, when a display is evaluated, the listed items are evaluated from
|
||
left to right and placed into a new container of the appropriate type.</p>
|
||
<p id="index-11">For tuple, list and set (but not dict) displays, any item in the display may
|
||
be prefixed with an asterisk (<code class="docutils literal notranslate"><span class="pre">*</span></code>).
|
||
This denotes <a class="reference internal" href="#iterable-unpacking"><span class="std std-ref">iterable unpacking</span></a>.
|
||
At runtime, the asterisk-prefixed expression must evaluate to an iterable,
|
||
whose contents are inserted into the container at the location of
|
||
the unpacking. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">numbers</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="p">[</span><span class="o">*</span><span class="n">numbers</span><span class="p">,</span> <span class="s1">'word'</span><span class="p">,</span> <span class="o">*</span><span class="n">numbers</span><span class="p">]</span>
|
||
<span class="go">[1, 2, 'word', 1, 2]</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Dictionary displays use a similar mechanism called
|
||
<em>dictionary unpacking</em>, denoted with a double
|
||
asterisk (<code class="docutils literal notranslate"><span class="pre">**</span></code>).
|
||
See <a class="reference internal" href="#dict"><span class="std std-ref">Dictionary displays</span></a> for details.</p>
|
||
<p>A more advanced form of displays are <em class="dfn">comprehensions</em>, where items are
|
||
computed via a set of looping and filtering instructions.
|
||
See the <a class="reference internal" href="#comprehensions"><span class="std std-ref">Comprehensions</span></a> section for details.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">Added in version 3.5: </span>Iterable and dictionary unpacking in displays, originally proposed
|
||
by <span class="target" id="index-12"></span><a class="pep reference external" href="https://peps.python.org/pep-0448/"><strong>PEP 448</strong></a>.</p>
|
||
</div>
|
||
<section id="list-displays">
|
||
<span id="lists"></span><h4><span class="section-number">6.2.5.1. </span>List displays<a class="headerlink" href="#list-displays" title="Link to this heading">¶</a></h4>
|
||
<p id="index-13">A <em class="dfn">list display</em> is a possibly empty series of expressions enclosed in
|
||
square brackets. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">[</span><span class="s2">"one"</span><span class="p">,</span> <span class="s2">"two"</span><span class="p">,</span> <span class="s2">"three"</span><span class="p">]</span>
|
||
<span class="go">['one', 'two', 'three']</span>
|
||
<span class="gp">>>> </span><span class="p">[</span><span class="s2">"one"</span><span class="p">]</span> <span class="c1"># One-element list</span>
|
||
<span class="go">['one']</span>
|
||
<span class="gp">>>> </span><span class="p">[]</span> <span class="c1"># empty list</span>
|
||
<span class="go">[]</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>See <a class="reference internal" href="#displays"><span class="std std-ref">Container displays</span></a> for general information on displays.</p>
|
||
<p>The formal grammar for list displays is:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-list">list</strong>: <span class="sx">'['</span> [<a class="reference internal" href="#grammar-token-python-grammar-flexible_expression_list"><code class="xref docutils literal notranslate"><span class="pre">flexible_expression_list</span></code></a>] <span class="sx">']'</span>
|
||
</pre>
|
||
</section>
|
||
<section id="set-displays">
|
||
<span id="set"></span><h4><span class="section-number">6.2.5.2. </span>Set displays<a class="headerlink" href="#set-displays" title="Link to this heading">¶</a></h4>
|
||
<p id="index-14">A <em class="dfn">set display</em> is a <em>non-empty</em> series of expressions enclosed in
|
||
curly braces. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">{</span><span class="s2">"one"</span><span class="p">,</span> <span class="s2">"two"</span><span class="p">,</span> <span class="s2">"three"</span><span class="p">}</span>
|
||
<span class="go">{'one', 'three', 'two'}</span>
|
||
<span class="gp">>>> </span><span class="p">{</span><span class="s2">"one"</span><span class="p">}</span> <span class="c1"># One-element set</span>
|
||
<span class="go">{'one'}</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>See <a class="reference internal" href="#displays"><span class="std std-ref">Container displays</span></a> for general information on displays.</p>
|
||
<p>There is no special syntax for the empty set.
|
||
The <code class="docutils literal notranslate"><span class="pre">{}</span></code> literal is a <a class="reference internal" href="#dict"><span class="std std-ref">dictionary display</span></a> that constructs an
|
||
empty dictionary.
|
||
Call <a class="reference internal" href="../builtins/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set()</span></code></a> with no arguments to get an empty set.</p>
|
||
<p>The formal grammar for set displays is:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-set">set</strong>: <span class="sx">'{'</span> <a class="reference internal" href="#grammar-token-python-grammar-flexible_expression_list"><code class="xref docutils literal notranslate"><span class="pre">flexible_expression_list</span></code></a> <span class="sx">'}'</span>
|
||
</pre>
|
||
</section>
|
||
<section id="tuple-displays">
|
||
<span id="index-16"></span><span id="tuple-display"></span><span id="index-15"></span><h4><span class="section-number">6.2.5.3. </span>Tuple displays<a class="headerlink" href="#tuple-displays" title="Link to this heading">¶</a></h4>
|
||
<p>A <em class="dfn">tuple display</em> is a series of expressions enclosed in
|
||
parentheses. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </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="go">(1, 2)</span>
|
||
<span class="gp">>>> </span><span class="p">()</span> <span class="c1"># an empty tuple</span>
|
||
<span class="go">()</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>See <a class="reference internal" href="#displays"><span class="std std-ref">Container displays</span></a> for general information on displays.</p>
|
||
<p>To avoid ambiguity, if a tuple display has exactly one element,
|
||
it requires a trailing comma.
|
||
Without it, you get a <a class="reference internal" href="#parenthesized"><span class="std std-ref">parenthesized group</span></a>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">(</span><span class="s1">'single'</span><span class="p">,)</span> <span class="c1"># single-element tuple</span>
|
||
<span class="go">('single',)</span>
|
||
<span class="gp">>>> </span><span class="p">(</span><span class="s1">'single'</span><span class="p">)</span> <span class="c1"># no comma: single string</span>
|
||
<span class="go">'single'</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>To put it in other words, a tuple display is a parenthesized list of either:</p>
|
||
<ul class="simple">
|
||
<li><p>two or more comma-separated expressions, or</p></li>
|
||
<li><p>zero or more expressions, each followed by a comma.</p></li>
|
||
</ul>
|
||
<p>Since tuples are immutable, <a class="reference internal" href="#literals-identity"><span class="std std-ref">object identity rules for literals</span></a>
|
||
also apply to tuples: at runtime, two occurrences of tuples with the same
|
||
values may or may not yield the same object.</p>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">Note</p>
|
||
<p>Python’s syntax also includes <a class="reference internal" href="#exprlists"><span class="std std-ref">expression lists</span></a>,
|
||
where a comma-separated list of expressions is <em>not</em> enclosed in parentheses
|
||
but evaluates to tuple.</p>
|
||
<p>In other words, when it comes to tuple syntax, the comma is more important
|
||
that the use of parentheses.
|
||
Only the empty tuple is spelled without a comma.</p>
|
||
</div>
|
||
<p>The formal grammar for tuple displays is:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-tuple">tuple</strong>:
|
||
| <span class="sx">'('</span> <a class="reference internal" href="#grammar-token-python-grammar-flexible_expression"><code class="xref docutils literal notranslate"><span class="pre">flexible_expression</span></code></a> (<span class="sx">','</span> <a class="reference internal" href="#grammar-token-python-grammar-flexible_expression"><code class="xref docutils literal notranslate"><span class="pre">flexible_expression</span></code></a>)+ [<span class="sx">','</span>] <span class="sx">')'</span>
|
||
| <span class="sx">'('</span> <a class="reference internal" href="#grammar-token-python-grammar-flexible_expression"><code class="xref docutils literal notranslate"><span class="pre">flexible_expression</span></code></a> <span class="sx">','</span> <span class="sx">')'</span>
|
||
| <span class="sx">'('</span> <span class="sx">')'</span>
|
||
</pre>
|
||
</section>
|
||
<section id="dictionary-displays">
|
||
<span id="dict"></span><h4><span class="section-number">6.2.5.4. </span>Dictionary displays<a class="headerlink" href="#dictionary-displays" title="Link to this heading">¶</a></h4>
|
||
<p id="index-17">A <em class="dfn">dictionary display</em> is a possibly empty series of <em class="dfn">dict items</em>
|
||
enclosed in curly braces.
|
||
Each dict item is a colon-separated pair of expressions: the <em class="dfn">key</em>
|
||
and its associated <em class="dfn">value</em>.
|
||
For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">{</span><span class="mi">1</span><span class="p">:</span> <span class="s1">'one'</span><span class="p">,</span> <span class="mi">2</span><span class="p">:</span> <span class="s1">'two'</span><span class="p">}</span>
|
||
<span class="go">{1: 'one', 2: 'two'}</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>At runtime, when a dictionary comprehension is evaluated, the expressions
|
||
are evaluated from left to right.
|
||
Each key object is used as a key into the dictionary to store the
|
||
corresponding value.
|
||
This means that you can specify the same key multiple times in the
|
||
comprehension, and the final dictionary’s value for a given key will be the
|
||
last one given.
|
||
For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">{</span>
|
||
<span class="gp">... </span> <span class="mi">1</span><span class="p">:</span> <span class="s1">'this will be overridden'</span><span class="p">,</span>
|
||
<span class="gp">... </span> <span class="mi">2</span><span class="p">:</span> <span class="s1">'two'</span><span class="p">,</span>
|
||
<span class="gp">... </span> <span class="mi">1</span><span class="p">:</span> <span class="s1">'also overridden'</span><span class="p">,</span>
|
||
<span class="gp">... </span> <span class="mi">1</span><span class="p">:</span> <span class="s1">'one'</span><span class="p">,</span>
|
||
<span class="gp">... </span><span class="p">}</span>
|
||
<span class="go">{1: 'one', 2: 'two'}</span>
|
||
</pre></div>
|
||
</div>
|
||
<p id="dict-unpacking"><span id="index-18"></span>Instead of a key-value pair, a dict item may be an expression prefixed by
|
||
a double asterisk <code class="docutils literal notranslate"><span class="pre">**</span></code>. This denotes <em class="dfn">dictionary unpacking</em>.
|
||
At runtime, the expression must evaluate to a <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a>;
|
||
each item of the mapping is added to the new dictionary.
|
||
As with key-value pairs, later values replace values already set by
|
||
earlier items and unpackings.
|
||
This may be used to override a set of defaults:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">defaults</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'color'</span><span class="p">:</span> <span class="s1">'blue'</span><span class="p">,</span> <span class="s1">'count'</span><span class="p">:</span> <span class="mi">8</span><span class="p">}</span>
|
||
<span class="gp">>>> </span><span class="n">overrides</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'color'</span><span class="p">:</span> <span class="s1">'yellow'</span><span class="p">}</span>
|
||
<span class="gp">>>> </span><span class="p">{</span><span class="o">**</span><span class="n">defaults</span><span class="p">,</span> <span class="o">**</span><span class="n">overrides</span><span class="p">}</span>
|
||
<span class="go">{'color': 'yellow', 'count': 8}</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">Added in version 3.5: </span>Unpacking into dictionary displays, originally proposed by <span class="target" id="index-19"></span><a class="pep reference external" href="https://peps.python.org/pep-0448/"><strong>PEP 448</strong></a>.</p>
|
||
</div>
|
||
<p>The formal grammar for dict displays is:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-dict">dict</strong>: <span class="sx">'{'</span> [<a class="reference internal" href="#grammar-token-python-grammar-double_starred_kvpairs"><code class="xref docutils literal notranslate"><span class="pre">double_starred_kvpairs</span></code></a>] <span class="sx">'}'</span>
|
||
<strong id="grammar-token-python-grammar-double_starred_kvpairs">double_starred_kvpairs</strong>: <span class="sx">','</span>.<a class="reference internal" href="#grammar-token-python-grammar-double_starred_kvpair"><code class="xref docutils literal notranslate"><span class="pre">double_starred_kvpair</span></code></a>+ [<span class="sx">','</span>]
|
||
<strong id="grammar-token-python-grammar-double_starred_kvpair">double_starred_kvpair</strong>: <span class="sx">'**'</span> <a class="reference internal" href="#grammar-token-python-grammar-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-kvpair"><code class="xref docutils literal notranslate"><span class="pre">kvpair</span></code></a>
|
||
<strong id="grammar-token-python-grammar-kvpair">kvpair</strong>: <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> <span class="sx">':'</span> <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
|
||
</pre>
|
||
</section>
|
||
</section>
|
||
<section id="comprehensions">
|
||
<span id="index-20"></span><span id="id4"></span><h3><span class="section-number">6.2.6. </span>Comprehensions<a class="headerlink" href="#comprehensions" title="Link to this heading">¶</a></h3>
|
||
<p>List, set and dictionary <em class="dfn">comprehensions</em> are a form of
|
||
<a class="reference internal" href="#displays"><span class="std std-ref">container displays</span></a> where items are computed via a set of
|
||
looping and filtering instructions rather than listed explicitly.</p>
|
||
<p>In its simplest form, a comprehension consists of a single expression
|
||
followed by a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause.
|
||
The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause has the same syntax as the header of a
|
||
<a class="reference internal" href="compound_stmts.html#for"><span class="std std-ref">for statement</span></a>, without a trailing colon.</p>
|
||
<p>For example, a list of the first ten squares is:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">[</span><span class="n">x</span><span class="o">**</span><span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)]</span>
|
||
<span class="go">[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>At run time, a list comprehension creates a new list.
|
||
The expression after <code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code> must evaluate to an <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a>.
|
||
For each element of this iterable, the element is bound to the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code>
|
||
clause’s target as in a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> statement, then the expression
|
||
before <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> is evaluated with the target in scope and the result
|
||
is added to the new list.
|
||
Thus, the example above is roughly equivalent to defining and calling
|
||
the following function:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">make_list_of_squares</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
|
||
<span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
|
||
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
|
||
<span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">x</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
|
||
<span class="k">return</span> <span class="n">result</span>
|
||
|
||
<span class="n">make_list_of_squares</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Set comprehensions work similarly.
|
||
For example, here is a set of lowercase letters:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">{</span><span class="n">x</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'A'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'C'</span><span class="p">]}</span>
|
||
<span class="go">{'c', 'a', 'b'}</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>At run time, this corresponds roughly to calling this function:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">make_lowercase_set</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
|
||
<span class="n">result</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
|
||
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
|
||
<span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">x</span><span class="o">.</span><span class="n">lower</span><span class="p">())</span>
|
||
<span class="k">return</span> <span class="n">result</span>
|
||
|
||
<span class="n">make_lowercase_set</span><span class="p">([</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'A'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'C'</span><span class="p">])</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Dictionary comprehensions start with a colon-separated key-value pair instead
|
||
of an expression. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">{</span><span class="n">func</span><span class="o">.</span><span class="vm">__name__</span><span class="p">:</span> <span class="n">func</span> <span class="k">for</span> <span class="n">func</span> <span class="ow">in</span> <span class="p">[</span><span class="nb">print</span><span class="p">,</span> <span class="nb">hex</span><span class="p">,</span> <span class="nb">any</span><span class="p">]}</span>
|
||
<span class="go">{'print': <built-in function print>,</span>
|
||
<span class="go"> 'hex': <built-in function hex>,</span>
|
||
<span class="go"> 'any': <built-in function any>}</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>At run time, this corresponds roughly to:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">make_dict_mapping_names_to_functions</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
|
||
<span class="n">result</span> <span class="o">=</span> <span class="p">{}</span>
|
||
<span class="k">for</span> <span class="n">func</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
|
||
<span class="n">result</span><span class="p">[</span><span class="n">func</span><span class="o">.</span><span class="vm">__name__</span><span class="p">]</span> <span class="o">=</span> <span class="n">func</span>
|
||
<span class="k">return</span> <span class="n">result</span>
|
||
|
||
<span class="n">iterable</span><span class="p">([</span><span class="nb">print</span><span class="p">,</span> <span class="nb">hex</span><span class="p">,</span> <span class="nb">any</span><span class="p">])</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>As in other kinds of dictionary displays, the same key may be specified
|
||
multiple times.
|
||
Earlier values are overwritten by ones that are evaluated later.</p>
|
||
<p>There are no <em>tuple comprehensions</em>.
|
||
A similar syntax is instead used for <a class="reference internal" href="#genexpr"><span class="std std-ref">generator expressions</span></a>,
|
||
from which you can construct a tuple like this:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">tuple</span><span class="p">(</span><span class="n">x</span><span class="o">**</span><span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
|
||
<span class="go">(0, 1, 4, 9, 16, 25, 36, 49, 64, 81)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.8: </span>Prior to Python 3.8, in dict comprehensions, the evaluation order of key
|
||
and value was not well-defined. In CPython, the value was evaluated before
|
||
the key. Starting with 3.8, the key is evaluated before the value, as
|
||
proposed by <span class="target" id="index-21"></span><a class="pep reference external" href="https://peps.python.org/pep-0572/"><strong>PEP 572</strong></a>.</p>
|
||
</div>
|
||
<section id="filtering-in-comprehensions">
|
||
<span id="index-22"></span><h4><span class="section-number">6.2.6.1. </span>Filtering in comprehensions<a class="headerlink" href="#filtering-in-comprehensions" title="Link to this heading">¶</a></h4>
|
||
<p>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause may be followed by an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> clause
|
||
with an expression.</p>
|
||
<p>For example, a list of names from the <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module
|
||
that start with <code class="docutils literal notranslate"><span class="pre">f</span></code> is:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">[</span><span class="n">name</span> <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="nb">vars</span><span class="p">(</span><span class="n">math</span><span class="p">)</span> <span class="k">if</span> <span class="n">name</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">'f'</span><span class="p">)]</span>
|
||
<span class="go">['fabs', 'factorial', 'floor', 'fma', 'fmod', 'frexp', 'fsum']</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>At run time, the expression after <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> is evaluated before
|
||
each element is added to the resulting container, and if it is false,
|
||
the element is skipped.
|
||
Thus, the above example roughly corresponds to defining and calling the
|
||
following function:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">get_math_f_names</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
|
||
<span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
|
||
<span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
|
||
<span class="k">if</span> <span class="n">name</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">'f'</span><span class="p">):</span>
|
||
<span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
|
||
<span class="k">return</span> <span class="n">result</span>
|
||
|
||
<span class="n">get_math_f_names</span><span class="p">(</span><span class="nb">vars</span><span class="p">(</span><span class="n">math</span><span class="p">))</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Filtering is a special case of more complex comprehensions.
|
||
See the next section for a more formal description.</p>
|
||
</section>
|
||
<section id="complex-comprehensions">
|
||
<span id="id5"></span><h4><span class="section-number">6.2.6.2. </span>Complex comprehensions<a class="headerlink" href="#complex-comprehensions" title="Link to this heading">¶</a></h4>
|
||
<p>Generally, a comprehension’s initial <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause may be followed by
|
||
zero or more additional <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> clauses.
|
||
For example, here is a list of names exposed by two Python modules,
|
||
filtered to only include names that start with <code class="docutils literal notranslate"><span class="pre">a</span></code>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">array</span>
|
||
<span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">math</span>
|
||
<span class="gp">>>> </span><span class="p">[</span>
|
||
<span class="gp">... </span> <span class="n">name</span>
|
||
<span class="gp">... </span> <span class="k">for</span> <span class="n">module</span> <span class="ow">in</span> <span class="p">[</span><span class="n">array</span><span class="p">,</span> <span class="n">math</span><span class="p">]</span>
|
||
<span class="gp">... </span> <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="nb">vars</span><span class="p">(</span><span class="n">module</span><span class="p">)</span>
|
||
<span class="gp">... </span> <span class="k">if</span> <span class="n">name</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">'a'</span><span class="p">)</span>
|
||
<span class="gp">... </span><span class="p">]</span>
|
||
<span class="go">['array', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh']</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>At run time, this roughly corresponds to defining and calling:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">get_a_names</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
|
||
<span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
|
||
<span class="k">for</span> <span class="n">module</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
|
||
<span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="nb">vars</span><span class="p">(</span><span class="n">module</span><span class="p">):</span>
|
||
<span class="k">if</span> <span class="n">name</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">'a'</span><span class="p">):</span>
|
||
<span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
|
||
<span class="k">return</span> <span class="n">result</span>
|
||
|
||
<span class="n">get_a_names</span><span class="p">([</span><span class="n">array</span><span class="p">,</span> <span class="n">math</span><span class="p">])</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>The elements of the new container are those that would be produced by
|
||
considering each of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> clauses a block,
|
||
nesting from left to right, and evaluating the expression to produce an
|
||
element (or dictionary entry) each time the innermost block is reached.</p>
|
||
<p>Aside from the iterable expression in the leftmost <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause,
|
||
the comprehension is executed in a separate implicitly nested scope.
|
||
This ensures that names assigned to in the target list don’t “leak” into
|
||
the enclosing scope.
|
||
For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="s1">'old value'</span>
|
||
<span class="gp">>>> </span><span class="p">[</span><span class="n">x</span><span class="o">**</span><span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)]</span> <span class="c1"># this `x` is local to the comprehension</span>
|
||
<span class="gp">>>> </span><span class="n">x</span>
|
||
<span class="go">'old value'</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>The iterable expression in the leftmost <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause is evaluated
|
||
directly in the enclosing scope and then passed as an argument to the implicitly
|
||
nested scope.</p>
|
||
<p>Subsequent <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clauses and any filter condition in the
|
||
leftmost <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause cannot be evaluated in the enclosing scope as
|
||
they may depend on the values obtained from the leftmost iterable.</p>
|
||
<p>To ensure the comprehension always results in a container of the appropriate
|
||
type, <code class="docutils literal notranslate"><span class="pre">yield</span></code> and <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> expressions are prohibited in the implicitly
|
||
nested scope.</p>
|
||
<p><a class="reference internal" href="#assignment-expressions"><span class="std std-ref">Assignment expressions</span></a> are not allowed
|
||
inside comprehension iterable expressions (that is, the expressions after
|
||
the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code> keyword), nor anywhere within comprehensions that
|
||
appear directly in a class definition.</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.8: </span><code class="docutils literal notranslate"><span class="pre">yield</span></code> and <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> prohibited in the implicitly nested scope.</p>
|
||
</div>
|
||
</section>
|
||
<section id="unpacking-in-comprehensions">
|
||
<span id="unpacking-comprehensions"></span><h4><span class="section-number">6.2.6.3. </span>Unpacking in comprehensions<a class="headerlink" href="#unpacking-in-comprehensions" title="Link to this heading">¶</a></h4>
|
||
<p>If the expression of a list or set comprehension is starred, the result will
|
||
be <a class="reference internal" href="#iterable-unpacking"><span class="std std-ref">unpacked</span></a> to produce
|
||
zero or more elements.</p>
|
||
<p>This is often used for “flattening” lists, for example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">students</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'Petr'</span><span class="p">,</span> <span class="s1">'Blaise'</span><span class="p">,</span> <span class="s1">'Jarka'</span><span class="p">]</span>
|
||
<span class="gp">>>> </span><span class="n">teachers</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'Salim'</span><span class="p">,</span> <span class="s1">'Bartosz'</span><span class="p">]</span>
|
||
<span class="gp">>>> </span><span class="n">lists_of_people</span> <span class="o">=</span> <span class="p">[</span><span class="n">students</span><span class="p">,</span> <span class="n">teachers</span><span class="p">]</span>
|
||
<span class="gp">>>> </span><span class="p">[</span><span class="o">*</span><span class="n">people</span> <span class="k">for</span> <span class="n">people</span> <span class="ow">in</span> <span class="n">lists_of_people</span><span class="p">]</span>
|
||
<span class="go">['Petr', 'Blaise', 'Jarka', 'Salim', 'Bartosz']</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>At run time, this comprehension roughly corresponds to:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">flatten_names</span><span class="p">(</span><span class="n">lists_of_people</span><span class="p">):</span>
|
||
<span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
|
||
<span class="k">for</span> <span class="n">people</span> <span class="ow">in</span> <span class="n">lists_of_people</span><span class="p">:</span>
|
||
<span class="n">result</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">people</span><span class="p">)</span>
|
||
<span class="k">return</span> <span class="n">result</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>In dict comprehensions, a double-starred expression will be evaluated and
|
||
then unpacked using <a class="reference internal" href="#dict-unpacking"><span class="std std-ref">dictionary unpacking</span></a>,
|
||
inserting zero or more key/value pairs into the new dictionary.
|
||
As in other kinds of dictionary displays, if the same key is specified
|
||
multiple times, the associated value in the resulting dictionary
|
||
will be the last one specified.</p>
|
||
<p>For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">system_defaults</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'color'</span><span class="p">:</span> <span class="s1">'blue'</span><span class="p">,</span> <span class="s1">'count'</span><span class="p">:</span> <span class="mi">8</span><span class="p">}</span>
|
||
<span class="gp">>>> </span><span class="n">user_defaults</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'color'</span><span class="p">:</span> <span class="s1">'yellow'</span><span class="p">}</span>
|
||
<span class="gp">>>> </span><span class="n">overrides</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'count'</span><span class="p">:</span> <span class="mi">5</span><span class="p">}</span>
|
||
|
||
<span class="gp">>>> </span><span class="n">configuration_sets</span> <span class="o">=</span> <span class="p">[</span><span class="n">system_defaults</span><span class="p">,</span> <span class="n">user_defaults</span><span class="p">,</span> <span class="n">overrides</span><span class="p">]</span>
|
||
|
||
<span class="gp">>>> </span><span class="p">{</span><span class="o">**</span><span class="n">d</span> <span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="n">configuration_sets</span><span class="p">}</span>
|
||
<span class="go">{'color': 'yellow', 'count': 5}</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">Added in version 3.15: </span>Unpacking in comprehensions using the <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">**</span></code> operators
|
||
was introduced in <span class="target" id="index-23"></span><a class="pep reference external" href="https://peps.python.org/pep-0798/"><strong>PEP 798</strong></a>.</p>
|
||
</div>
|
||
</section>
|
||
<section id="asynchronous-comprehensions">
|
||
<span id="index-24"></span><h4><span class="section-number">6.2.6.4. </span>Asynchronous comprehensions<a class="headerlink" href="#asynchronous-comprehensions" title="Link to this heading">¶</a></h4>
|
||
<p>In an <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> function, an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code>
|
||
clause may be used to iterate over a <a class="reference internal" href="../glossary.html#term-asynchronous-iterator"><span class="xref std std-term">asynchronous iterator</span></a>.
|
||
A comprehension in an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> function may consist of either a
|
||
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> clause following the leading
|
||
expression, may contain additional <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code>
|
||
clauses, and may also use <a class="reference internal" href="#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expressions.</p>
|
||
<p>If a comprehension contains <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> clauses, or if it contains
|
||
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code> expressions or other asynchronous comprehensions anywhere except
|
||
the iterable expression in the leftmost <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause, it is called an
|
||
<em class="dfn">asynchronous comprehension</em>. An asynchronous comprehension may suspend the
|
||
execution of the coroutine function in which it appears.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">Added in version 3.6: </span>Asynchronous comprehensions were introduced in <span class="target" id="index-25"></span><a class="pep reference external" href="https://peps.python.org/pep-0530/"><strong>PEP 530</strong></a>.</p>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.11: </span>Asynchronous comprehensions are now allowed inside comprehensions in
|
||
asynchronous functions. Outer comprehensions implicitly become
|
||
asynchronous.</p>
|
||
</div>
|
||
</section>
|
||
<section id="formal-grammar-for-comprehensions">
|
||
<span id="comprehension-grammar"></span><h4><span class="section-number">6.2.6.5. </span>Formal grammar for comprehensions<a class="headerlink" href="#formal-grammar-for-comprehensions" title="Link to this heading">¶</a></h4>
|
||
<p>The formal grammar for comprehensions is:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-listcomp">listcomp</strong>: <span class="sx">'['</span> <a class="reference internal" href="#grammar-token-python-grammar-comprehension"><code class="xref docutils literal notranslate"><span class="pre">comprehension</span></code></a> <span class="sx">']'</span>
|
||
<strong id="grammar-token-python-grammar-setcomp">setcomp</strong>: <span class="sx">'{'</span> <a class="reference internal" href="#grammar-token-python-grammar-comprehension"><code class="xref docutils literal notranslate"><span class="pre">comprehension</span></code></a> <span class="sx">'}'</span>
|
||
<strong id="grammar-token-python-grammar-comprehension">comprehension</strong>: <a class="reference internal" href="#grammar-token-python-grammar-flexible_expression"><code class="xref docutils literal notranslate"><span class="pre">flexible_expression</span></code></a> <a class="reference internal" href="#grammar-token-python-grammar-for_if_clause"><code class="xref docutils literal notranslate"><span class="pre">for_if_clause</span></code></a>+
|
||
|
||
<strong id="grammar-token-python-grammar-dictcomp">dictcomp</strong>:
|
||
| <span class="sx">'{'</span> <a class="reference internal" href="#grammar-token-python-grammar-kvpair"><code class="xref docutils literal notranslate"><span class="pre">kvpair</span></code></a> <a class="reference internal" href="#grammar-token-python-grammar-for_if_clause"><code class="xref docutils literal notranslate"><span class="pre">for_if_clause</span></code></a>+ <span class="sx">'}'</span>
|
||
| <span class="sx">'{'</span> <span class="sx">'**'</span> <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> <a class="reference internal" href="#grammar-token-python-grammar-for_if_clause"><code class="xref docutils literal notranslate"><span class="pre">for_if_clause</span></code></a>+ <span class="sx">'}'</span>
|
||
|
||
<strong id="grammar-token-python-grammar-for_if_clause">for_if_clause</strong>:
|
||
| [<span class="sx">'async'</span>] <span class="sx">'for'</span> <a class="reference internal" href="simple_stmts.html#grammar-token-python-grammar-target_list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a> <span class="sx">'in'</span> <a class="reference internal" href="#grammar-token-python-grammar-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> (<span class="sx">'if'</span> <a class="reference internal" href="#grammar-token-python-grammar-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a>)*
|
||
</pre>
|
||
</section>
|
||
</section>
|
||
<section id="generator-expressions">
|
||
<span id="genexpr"></span><h3><span class="section-number">6.2.7. </span>Generator expressions<a class="headerlink" href="#generator-expressions" title="Link to this heading">¶</a></h3>
|
||
<p id="index-26">The syntax for <em class="dfn">generator expressions</em> is the same as for
|
||
list <a class="reference internal" href="#comprehensions"><span class="std std-ref">comprehensions</span></a>, except that they are enclosed in
|
||
parentheses instead of brackets.
|
||
For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">iterator</span> <span class="o">=</span> <span class="p">(</span><span class="n">x</span> <span class="o">**</span> <span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
|
||
<span class="gp">>>> </span><span class="n">iterator</span>
|
||
<span class="go"><generator object <genexpr> at ...></span>
|
||
</pre></div>
|
||
</div>
|
||
<p>At runtime, a generator expression evaluates to a <a class="reference internal" href="../glossary.html#term-generator-iterator"><span class="xref std std-term">generator iterator</span></a>
|
||
which yields the same values as the corresponding list comprehension:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">iterator</span><span class="p">)</span>
|
||
<span class="go">[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Thus, the example above is roughly equivalent to defining and calling
|
||
the following generator function:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">make_generator_of_squares</span><span class="p">(</span><span class="n">iterator</span><span class="p">):</span>
|
||
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">iterator</span><span class="p">:</span>
|
||
<span class="k">yield</span> <span class="n">x</span> <span class="o">**</span> <span class="mi">2</span>
|
||
|
||
<span class="n">make_generator_of_squares</span><span class="p">(</span><span class="nb">iter</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)))</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>The enclosing parentheses can be omitted in calls when the generator
|
||
expression is the only positional argument and there are no keyword
|
||
arguments.
|
||
See the <a class="reference internal" href="#calls"><span class="std std-ref">Calls section</span></a> for details.
|
||
For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># The parentheses after `sum` are part of the call syntax:</span>
|
||
<span class="o">>>></span> <span class="nb">sum</span><span class="p">(</span><span class="n">x</span> <span class="o">**</span> <span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
|
||
<span class="mi">285</span>
|
||
|
||
<span class="c1"># The generator needs its own parentheses if it's not the only argument:</span>
|
||
<span class="o">>>></span> <span class="nb">sum</span><span class="p">((</span><span class="n">x</span> <span class="o">**</span> <span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)),</span> <span class="n">start</span><span class="o">=</span><span class="mi">1000</span><span class="p">)</span>
|
||
<span class="mi">1285</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>The iterable expression in the leftmost <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause is
|
||
evaluated immediately, so that an error raised by this expression will be
|
||
emitted at the point where the generator expression is defined,
|
||
rather than at the point where the first value is retrieved:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">(</span><span class="n">x</span> <span class="o">**</span> <span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">nonexistent_iterable</span><span class="p">)</span>
|
||
<span class="gt">Traceback (most recent call last):</span>
|
||
<span class="w"> </span><span class="c">...</span>
|
||
<span class="gr">NameError</span>: <span class="n">name 'nonexistent_iterable' is not defined</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>After the expression is evaluated, an iterator is created
|
||
from the result, as if <a class="reference internal" href="../builtins/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> was called on it.
|
||
Any error raised when creating the iterator is also emitted immediately:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="p">(</span><span class="n">x</span> <span class="o">**</span> <span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="kc">None</span><span class="p">)</span>
|
||
<span class="gt">Traceback (most recent call last):</span>
|
||
<span class="w"> </span><span class="c">...</span>
|
||
<span class="gr">TypeError</span>: <span class="n">'NoneType' object is not iterable</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>All other expressions are evaluated lazily, in the same fashion as normal
|
||
generators (that is, when the iterator is asked to yield a value):</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">iterator</span> <span class="o">=</span> <span class="p">(</span><span class="n">nonexistent_value</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
|
||
<span class="gp">>>> </span><span class="n">iterator</span>
|
||
<span class="go"><generator object <genexpr> at ...></span>
|
||
<span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">iterator</span><span class="p">)</span>
|
||
<span class="gt">Traceback (most recent call last):</span>
|
||
<span class="w"> </span><span class="c">...</span>
|
||
<span class="gr">NameError</span>: <span class="n">name 'nonexistent_value' is not defined</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">iterator</span> <span class="o">=</span> <span class="p">(</span><span class="n">x</span> <span class="o">*</span> <span class="n">y</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">nonexistent_iterable</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="n">iterator</span>
|
||
<span class="go"><generator object <genexpr> at ...></span>
|
||
<span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">iterator</span><span class="p">)</span>
|
||
<span class="gt">Traceback (most recent call last):</span>
|
||
<span class="w"> </span><span class="c">...</span>
|
||
<span class="gr">NameError</span>: <span class="n">name 'nonexistent_iterable' is not defined</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>To avoid interfering with the expected operation of the generator expression
|
||
itself, <code class="docutils literal notranslate"><span class="pre">yield</span></code> and <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> expressions are prohibited inside
|
||
the implicitly nested scope.</p>
|
||
<p>If a generator expression contains either <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code>
|
||
clauses or <a class="reference internal" href="#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expressions it is called an
|
||
<em class="dfn">asynchronous generator expression</em>.
|
||
An asynchronous generator expression returns a new asynchronous generator
|
||
object, which is an asynchronous iterator (see <a class="reference internal" href="datamodel.html#async-iterators"><span class="std std-ref">Asynchronous Iterators</span></a>).</p>
|
||
<p>The formal grammar for generator expressions is:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-generator_expression">generator_expression</strong>: <span class="sx">"("</span> <a class="reference internal" href="#grammar-token-python-grammar-comprehension"><code class="xref docutils literal notranslate"><span class="pre">comprehension</span></code></a> <span class="sx">")"</span>
|
||
</pre>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">Added in version 3.6: </span>Asynchronous generator expressions were introduced.</p>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.7: </span>Prior to Python 3.7, asynchronous generator expressions could
|
||
only appear in <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> coroutines. Starting
|
||
with 3.7, any function can use asynchronous generator expressions.</p>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.8: </span><code class="docutils literal notranslate"><span class="pre">yield</span></code> and <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> prohibited in the implicitly nested scope.</p>
|
||
</div>
|
||
</section>
|
||
<section id="yield-expressions">
|
||
<span id="yieldexpr"></span><h3><span class="section-number">6.2.8. </span>Yield expressions<a class="headerlink" href="#yield-expressions" title="Link to this heading">¶</a></h3>
|
||
<pre class="highlight" id="index-27">
|
||
<strong id="grammar-token-python-grammar-yield_atom">yield_atom</strong>: <span class="sx">"("</span> <a class="reference internal" href="#grammar-token-python-grammar-yield_expression"><code class="xref docutils literal notranslate"><span class="pre">yield_expression</span></code></a> <span class="sx">")"</span>
|
||
<strong id="grammar-token-python-grammar-yield_from">yield_from</strong>: <span class="sx">"yield"</span> <span class="sx">"from"</span> <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
|
||
<strong id="grammar-token-python-grammar-yield_expression">yield_expression</strong>: <span class="sx">"yield"</span> <a class="reference internal" href="#grammar-token-python-grammar-yield_list"><code class="xref docutils literal notranslate"><span class="pre">yield_list</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-yield_from"><code class="xref docutils literal notranslate"><span class="pre">yield_from</span></code></a>
|
||
</pre>
|
||
<p>The yield expression is used when defining a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a> function
|
||
or an <a class="reference internal" href="../glossary.html#term-asynchronous-generator"><span class="xref std std-term">asynchronous generator</span></a> function and
|
||
thus can only be used in the body of a function definition. Using a yield
|
||
expression in a function’s body causes that function to be a generator function,
|
||
and using it in an <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> function’s body causes that
|
||
coroutine function to be an asynchronous generator function. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">gen</span><span class="p">():</span> <span class="c1"># defines a generator function</span>
|
||
<span class="k">yield</span> <span class="mi">123</span>
|
||
|
||
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">agen</span><span class="p">():</span> <span class="c1"># defines an asynchronous generator function</span>
|
||
<span class="k">yield</span> <span class="mi">123</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Due to their side effects on the containing scope, <code class="docutils literal notranslate"><span class="pre">yield</span></code> expressions
|
||
are not permitted as part of the implicitly defined scopes used to
|
||
implement comprehensions and generator expressions.</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.8: </span>Yield expressions prohibited in the implicitly nested scopes used to
|
||
implement comprehensions and generator expressions.</p>
|
||
</div>
|
||
<p>Generator functions are described below, while asynchronous generator
|
||
functions are described separately in section
|
||
<a class="reference internal" href="#asynchronous-generator-functions"><span class="std std-ref">Asynchronous generator functions</span></a>.</p>
|
||
<p>When a generator function is called, it returns an iterator known as a
|
||
generator. That generator then controls the execution of the generator
|
||
function. The execution starts when one of the generator’s methods is called.
|
||
At that time, the execution proceeds to the first yield expression, where it is
|
||
suspended again, returning the value of <a class="reference internal" href="#grammar-token-python-grammar-yield_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">yield_list</span></code></a>
|
||
to the generator’s caller,
|
||
or <code class="docutils literal notranslate"><span class="pre">None</span></code> if <code class="xref std std-token docutils literal notranslate"><span class="pre">yield_list</span></code> is omitted.
|
||
By suspended, we mean that all local state is
|
||
retained, including the current bindings of local variables, the instruction
|
||
pointer, the internal evaluation stack, and the state of any exception handling.
|
||
When the execution is resumed by calling one of the generator’s methods, the
|
||
function can proceed exactly as if the yield expression were just another
|
||
external call. The value of the yield expression after resuming depends on the
|
||
method which resumed the execution. If <a class="reference internal" href="#generator.__next__" title="generator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> is used
|
||
(typically via either a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> or the <a class="reference internal" href="../builtins/functions.html#next" title="next"><code class="xref py py-func docutils literal notranslate"><span class="pre">next()</span></code></a> builtin) then the
|
||
result is <a class="reference internal" href="../builtins/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>. Otherwise, if <a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> is used, then
|
||
the result will be the value passed in to that method.</p>
|
||
<p id="index-28">All of this makes generator functions quite similar to coroutines; they yield
|
||
multiple times, they have more than one entry point and their execution can be
|
||
suspended. The only difference is that a generator function cannot control
|
||
where the execution should continue after it yields; the control is always
|
||
transferred to the generator’s caller.</p>
|
||
<p>Yield expressions are allowed anywhere in a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> construct. If the
|
||
generator is not resumed before it is
|
||
finalized (by reaching a zero reference count or by being garbage collected),
|
||
the generator-iterator’s <a class="reference internal" href="#generator.close" title="generator.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method will be called,
|
||
allowing any pending <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clauses to execute.</p>
|
||
<p id="index-29">When <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span> <span class="pre"><expr></span></code> is used, the supplied expression must be an
|
||
iterable. The values produced by iterating that iterable are passed directly
|
||
to the caller of the current generator’s methods. Any values passed in with
|
||
<a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> and any exceptions passed in with
|
||
<a class="reference internal" href="#generator.throw" title="generator.throw"><code class="xref py py-meth docutils literal notranslate"><span class="pre">throw()</span></code></a> are passed to the underlying iterator if it has the
|
||
appropriate methods. If this is not the case, then <code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code>
|
||
will raise <a class="reference internal" href="../builtins/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> or <a class="reference internal" href="../builtins/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>, while
|
||
<code class="xref py py-meth docutils literal notranslate"><span class="pre">throw()</span></code> will just raise the passed in exception immediately.</p>
|
||
<p>When the underlying iterator is complete, the <a class="reference internal" href="../builtins/exceptions.html#StopIteration.value" title="StopIteration.value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">value</span></code></a>
|
||
attribute of the raised <a class="reference internal" href="../builtins/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> instance becomes the value of
|
||
the yield expression. It can be either set explicitly when raising
|
||
<code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code>, or automatically when the subiterator is a generator
|
||
(by returning a value from the subgenerator).</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.3: </span>Added <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span> <span class="pre"><expr></span></code> to delegate control flow to a subiterator.</p>
|
||
</div>
|
||
<p>The parentheses may be omitted when the yield expression is the sole expression
|
||
on the right hand side of an assignment statement.</p>
|
||
<div class="admonition seealso">
|
||
<p class="admonition-title">See also</p>
|
||
<dl class="simple">
|
||
<dt><span class="target" id="index-30"></span><a class="pep reference external" href="https://peps.python.org/pep-0255/"><strong>PEP 255</strong></a> - Simple Generators</dt><dd><p>The proposal for adding generators and the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement to Python.</p>
|
||
</dd>
|
||
<dt><span class="target" id="index-31"></span><a class="pep reference external" href="https://peps.python.org/pep-0342/"><strong>PEP 342</strong></a> - Coroutines via Enhanced Generators</dt><dd><p>The proposal to enhance the API and syntax of generators, making them
|
||
usable as simple coroutines.</p>
|
||
</dd>
|
||
<dt><span class="target" id="index-32"></span><a class="pep reference external" href="https://peps.python.org/pep-0380/"><strong>PEP 380</strong></a> - Syntax for Delegating to a Subgenerator</dt><dd><p>The proposal to introduce the <a class="reference internal" href="#grammar-token-python-grammar-yield_from"><code class="xref std std-token docutils literal notranslate"><span class="pre">yield_from</span></code></a> syntax,
|
||
making delegation to subgenerators easy.</p>
|
||
</dd>
|
||
<dt><span class="target" id="index-33"></span><a class="pep reference external" href="https://peps.python.org/pep-0525/"><strong>PEP 525</strong></a> - Asynchronous Generators</dt><dd><p>The proposal that expanded on <span class="target" id="index-34"></span><a class="pep reference external" href="https://peps.python.org/pep-0492/"><strong>PEP 492</strong></a> by adding generator capabilities to
|
||
coroutine functions.</p>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
<section id="generator-iterator-methods">
|
||
<span id="generator-methods"></span><span id="index-35"></span><h4><span class="section-number">6.2.8.1. </span>Generator-iterator methods<a class="headerlink" href="#generator-iterator-methods" title="Link to this heading">¶</a></h4>
|
||
<p>This subsection describes the methods of a generator iterator. They can
|
||
be used to control the execution of a generator function.</p>
|
||
<p>Note that calling any of the generator methods below when the generator
|
||
is already executing raises a <a class="reference internal" href="../builtins/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception.</p>
|
||
<dl class="py method" id="index-36">
|
||
<dt class="sig sig-object py" id="generator.__next__">
|
||
<span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">__next__</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#generator.__next__" title="Link to this definition">¶</a></dt>
|
||
<dd><p>Starts the execution of a generator function or resumes it at the last
|
||
executed yield expression. When a generator function is resumed with a
|
||
<code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code> method, the current yield expression always
|
||
evaluates to <a class="reference internal" href="../builtins/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>. The execution then continues to the next yield
|
||
expression, where the generator is suspended again, and the value of the
|
||
<a class="reference internal" href="#grammar-token-python-grammar-yield_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">yield_list</span></code></a> is returned to <code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code>’s
|
||
caller. If the generator exits without yielding another value, a
|
||
<a class="reference internal" href="../builtins/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception is raised.</p>
|
||
<p>This method is normally called implicitly, e.g. by a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop, or
|
||
by the built-in <a class="reference internal" href="../builtins/functions.html#next" title="next"><code class="xref py py-func docutils literal notranslate"><span class="pre">next()</span></code></a> function.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="py method">
|
||
<dt class="sig sig-object py" id="generator.send">
|
||
<span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">send</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#generator.send" title="Link to this definition">¶</a></dt>
|
||
<dd><p>Resumes the execution and “sends” a value into the generator function. The
|
||
<em>value</em> argument becomes the result of the current yield expression. The
|
||
<code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code> method returns the next value yielded by the generator, or
|
||
raises <a class="reference internal" href="../builtins/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> if the generator exits without yielding another
|
||
value. When <code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code> is called to start the generator, it must be called
|
||
with <a class="reference internal" href="../builtins/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> as the argument, because there is no yield expression that
|
||
could receive the value.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="py method">
|
||
<dt class="sig sig-object py" id="generator.throw">
|
||
<span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">throw</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#generator.throw" title="Link to this definition">¶</a></dt>
|
||
<dt class="sig sig-object py">
|
||
<span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">throw</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">type</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">traceback</span></span></em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
|
||
<dd><p>Raises an exception at the point where the generator was paused,
|
||
and returns the next value yielded by the generator function. If the generator
|
||
exits without yielding another value, a <a class="reference internal" href="../builtins/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception is
|
||
raised. If the generator function does not catch the passed-in exception, or
|
||
raises a different exception, then that exception propagates to the caller.</p>
|
||
<p>In typical use, this is called with a single exception instance similar to the
|
||
way the <a class="reference internal" href="simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> keyword is used.</p>
|
||
<p>For backwards compatibility, however, the second signature is
|
||
supported, following a convention from older versions of Python.
|
||
The <em>type</em> argument should be an exception class, and <em>value</em>
|
||
should be an exception instance. If the <em>value</em> is not provided, the
|
||
<em>type</em> constructor is called to get an instance. If <em>traceback</em>
|
||
is provided, it is set on the exception, otherwise any existing
|
||
<a class="reference internal" href="../builtins/exceptions.html#BaseException.__traceback__" title="BaseException.__traceback__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__traceback__</span></code></a> attribute stored in <em>value</em> may
|
||
be cleared.</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.12: </span>The second signature (type[, value[, traceback]]) is deprecated and
|
||
may be removed in a future version of Python.</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="py method" id="index-37">
|
||
<dt class="sig sig-object py" id="generator.close">
|
||
<span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">close</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#generator.close" title="Link to this definition">¶</a></dt>
|
||
<dd><p>Raises a <a class="reference internal" href="../builtins/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> exception at the point where the generator
|
||
function was paused (equivalent to calling <code class="docutils literal notranslate"><span class="pre">throw(GeneratorExit)</span></code>).
|
||
The exception is raised by the yield expression where the generator was paused.
|
||
If the generator function catches the exception and returns a
|
||
value, this value is returned from <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code>. If the generator function
|
||
is already closed, or raises <code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code> (by not catching the
|
||
exception), <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> returns <a class="reference internal" href="../builtins/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>. If the generator yields a
|
||
value, a <a class="reference internal" href="../builtins/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised. If the generator raises any other
|
||
exception, it is propagated to the caller. If the generator has already
|
||
exited due to an exception or normal exit, <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> returns
|
||
<code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code> and has no other effect.</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.13: </span>If a generator returns a value upon being closed, the value is returned
|
||
by <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code>.</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
</section>
|
||
<section id="examples">
|
||
<span id="index-38"></span><h4><span class="section-number">6.2.8.2. </span>Examples<a class="headerlink" href="#examples" title="Link to this heading">¶</a></h4>
|
||
<p>Here is a simple example that demonstrates the behavior of generators and
|
||
generator functions:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">echo</span><span class="p">(</span><span class="n">value</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
|
||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Execution starts when 'next()' is called for the first time."</span><span class="p">)</span>
|
||
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
|
||
<span class="gp">... </span> <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
|
||
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
|
||
<span class="gp">... </span> <span class="n">value</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">value</span><span class="p">)</span>
|
||
<span class="gp">... </span> <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
|
||
<span class="gp">... </span> <span class="n">value</span> <span class="o">=</span> <span class="n">e</span>
|
||
<span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
|
||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Don't forget to clean up when 'close()' is called."</span><span class="p">)</span>
|
||
<span class="gp">...</span>
|
||
<span class="gp">>>> </span><span class="n">generator</span> <span class="o">=</span> <span class="n">echo</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="nb">next</span><span class="p">(</span><span class="n">generator</span><span class="p">))</span>
|
||
<span class="go">Execution starts when 'next()' is called for the first time.</span>
|
||
<span class="go">1</span>
|
||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="nb">next</span><span class="p">(</span><span class="n">generator</span><span class="p">))</span>
|
||
<span class="go">None</span>
|
||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">generator</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="mi">2</span><span class="p">))</span>
|
||
<span class="go">2</span>
|
||
<span class="gp">>>> </span><span class="n">generator</span><span class="o">.</span><span class="n">throw</span><span class="p">(</span><span class="ne">TypeError</span><span class="p">,</span> <span class="s2">"spam"</span><span class="p">)</span>
|
||
<span class="go">TypeError('spam',)</span>
|
||
<span class="gp">>>> </span><span class="n">generator</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
|
||
<span class="go">Don't forget to clean up when 'close()' is called.</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>For examples using <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code>, see <a class="reference internal" href="../whatsnew/3.3.html#pep-380"><span class="std std-ref">PEP 380: Syntax for Delegating to a Subgenerator</span></a> in “What’s New in
|
||
Python.”</p>
|
||
</section>
|
||
<section id="asynchronous-generator-functions">
|
||
<span id="id6"></span><h4><span class="section-number">6.2.8.3. </span>Asynchronous generator functions<a class="headerlink" href="#asynchronous-generator-functions" title="Link to this heading">¶</a></h4>
|
||
<p>The presence of a yield expression in a function or method defined using
|
||
<a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> further defines the function as an
|
||
<a class="reference internal" href="../glossary.html#term-asynchronous-generator"><span class="xref std std-term">asynchronous generator</span></a> function.</p>
|
||
<p>When an asynchronous generator function is called, it returns an
|
||
asynchronous iterator known as an asynchronous generator object.
|
||
That object then controls the execution of the generator function.
|
||
An asynchronous generator object is typically used in an
|
||
<a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> statement in a coroutine function analogously to
|
||
how a generator object would be used in a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement.</p>
|
||
<p>Calling one of the asynchronous generator’s methods returns an <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a>
|
||
object, and the execution starts when this object is awaited on. At that time,
|
||
the execution proceeds to the first yield expression, where it is suspended
|
||
again, returning the value of <a class="reference internal" href="#grammar-token-python-grammar-yield_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">yield_list</span></code></a> to the
|
||
awaiting coroutine. As with a generator, suspension means that all local state
|
||
is retained, including the current bindings of local variables, the instruction
|
||
pointer, the internal evaluation stack, and the state of any exception handling.
|
||
When the execution is resumed by awaiting on the next object returned by the
|
||
asynchronous generator’s methods, the function can proceed exactly as if the
|
||
yield expression were just another external call. The value of the yield
|
||
expression after resuming depends on the method which resumed the execution. If
|
||
<a class="reference internal" href="#agen.__anext__" title="agen.__anext__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__anext__()</span></code></a> is used then the result is <a class="reference internal" href="../builtins/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>. Otherwise, if
|
||
<a class="reference internal" href="#agen.asend" title="agen.asend"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asend()</span></code></a> is used, then the result will be the value passed in to that
|
||
method.</p>
|
||
<p>If an asynchronous generator happens to exit early by <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>, the caller
|
||
task being cancelled, or other exceptions, the generator’s async cleanup code
|
||
will run and possibly raise exceptions or access context variables in an
|
||
unexpected context–perhaps after the lifetime of tasks it depends, or
|
||
during the event loop shutdown when the async-generator garbage collection hook
|
||
is called.
|
||
To prevent this, the caller must explicitly close the async generator by calling
|
||
<a class="reference internal" href="#agen.aclose" title="agen.aclose"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code></a> method to finalize the generator and ultimately detach it
|
||
from the event loop.</p>
|
||
<p>In an asynchronous generator function, yield expressions are allowed anywhere
|
||
in a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> construct. However, if an asynchronous generator is not
|
||
resumed before it is finalized (by reaching a zero reference count or by
|
||
being garbage collected), then a yield expression within a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code>
|
||
construct could result in a failure to execute pending <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>
|
||
clauses. In this case, it is the responsibility of the event loop or
|
||
scheduler running the asynchronous generator to call the asynchronous
|
||
generator-iterator’s <a class="reference internal" href="#agen.aclose" title="agen.aclose"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code></a> method and run the resulting
|
||
coroutine object, thus allowing any pending <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clauses
|
||
to execute.</p>
|
||
<p>To take care of finalization upon event loop termination, an event loop should
|
||
define a <em>finalizer</em> function which takes an asynchronous generator-iterator and
|
||
presumably calls <a class="reference internal" href="#agen.aclose" title="agen.aclose"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code></a> and executes the coroutine.
|
||
This <em>finalizer</em> may be registered by calling <a class="reference internal" href="../library/sys.html#sys.set_asyncgen_hooks" title="sys.set_asyncgen_hooks"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.set_asyncgen_hooks()</span></code></a>.
|
||
When first iterated over, an asynchronous generator-iterator will store the
|
||
registered <em>finalizer</em> to be called upon finalization. For a reference example
|
||
of a <em>finalizer</em> method see the implementation of
|
||
<code class="docutils literal notranslate"><span class="pre">asyncio.Loop.shutdown_asyncgens</span></code> in <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/3.15/Lib/asyncio/base_events.py">Lib/asyncio/base_events.py</a>.</p>
|
||
<p>The expression <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span> <span class="pre"><expr></span></code> is a syntax error when used in an
|
||
asynchronous generator function.</p>
|
||
</section>
|
||
<section id="asynchronous-generator-iterator-methods">
|
||
<span id="asynchronous-generator-methods"></span><span id="index-39"></span><h4><span class="section-number">6.2.8.4. </span>Asynchronous generator-iterator methods<a class="headerlink" href="#asynchronous-generator-iterator-methods" title="Link to this heading">¶</a></h4>
|
||
<p>This subsection describes the methods of an asynchronous generator iterator,
|
||
which are used to control the execution of a generator function.</p>
|
||
<dl class="py method" id="index-40">
|
||
<dt class="sig sig-object py" id="agen.__anext__">
|
||
<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">__anext__</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#agen.__anext__" title="Link to this definition">¶</a></dt>
|
||
<dd><p>Returns an awaitable which when run starts to execute the asynchronous
|
||
generator or resumes it at the last executed yield expression. When an
|
||
asynchronous generator function is resumed with an <code class="xref py py-meth docutils literal notranslate"><span class="pre">__anext__()</span></code>
|
||
method, the current yield expression always evaluates to <a class="reference internal" href="../builtins/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> in the
|
||
returned awaitable, which when run will continue to the next yield
|
||
expression. The value of the <a class="reference internal" href="#grammar-token-python-grammar-yield_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">yield_list</span></code></a> of the
|
||
yield expression is the value of the <a class="reference internal" href="../builtins/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception raised by
|
||
the completing coroutine. If the asynchronous generator exits without
|
||
yielding another value, the awaitable instead raises a
|
||
<a class="reference internal" href="../builtins/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> exception, signalling that the asynchronous
|
||
iteration has completed.</p>
|
||
<p>This method is normally called implicitly by a <a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> loop.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="py method">
|
||
<dt class="sig sig-object py" id="agen.asend">
|
||
<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">asend</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#agen.asend" title="Link to this definition">¶</a></dt>
|
||
<dd><p>Returns an awaitable which when run resumes the execution of the
|
||
asynchronous generator. As with the <a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> method for a
|
||
generator, this “sends” a value into the asynchronous generator function,
|
||
and the <em>value</em> argument becomes the result of the current yield expression.
|
||
The awaitable returned by the <code class="xref py py-meth docutils literal notranslate"><span class="pre">asend()</span></code> method will return the next
|
||
value yielded by the generator as the value of the raised
|
||
<a class="reference internal" href="../builtins/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>, or raises <a class="reference internal" href="../builtins/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> if the
|
||
asynchronous generator exits without yielding another value. When
|
||
<code class="xref py py-meth docutils literal notranslate"><span class="pre">asend()</span></code> is called to start the asynchronous
|
||
generator, it must be called with <a class="reference internal" href="../builtins/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> as the argument,
|
||
because there is no yield expression that could receive the value.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="py method">
|
||
<dt class="sig sig-object py" id="agen.athrow">
|
||
<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">athrow</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#agen.athrow" title="Link to this definition">¶</a></dt>
|
||
<dt class="sig sig-object py">
|
||
<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">athrow</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">type</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">traceback</span></span></em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
|
||
<dd><p>Returns an awaitable that raises an exception of type <code class="docutils literal notranslate"><span class="pre">type</span></code> at the point
|
||
where the asynchronous generator was paused, and returns the next value
|
||
yielded by the generator function as the value of the raised
|
||
<a class="reference internal" href="../builtins/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception. If the asynchronous generator exits
|
||
without yielding another value, a <a class="reference internal" href="../builtins/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> exception is
|
||
raised by the awaitable.
|
||
If the generator function does not catch the passed-in exception, or
|
||
raises a different exception, then when the awaitable is run that exception
|
||
propagates to the caller of the awaitable.</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.12: </span>The second signature (type[, value[, traceback]]) is deprecated and
|
||
may be removed in a future version of Python.</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="py method" id="index-41">
|
||
<dt class="sig sig-object py" id="agen.aclose">
|
||
<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">aclose</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#agen.aclose" title="Link to this definition">¶</a></dt>
|
||
<dd><p>Returns an awaitable that when run will throw a <a class="reference internal" href="../builtins/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> into
|
||
the asynchronous generator function at the point where it was paused.
|
||
If the asynchronous generator function then exits gracefully, is already
|
||
closed, or raises <code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code> (by not catching the exception),
|
||
then the returned awaitable will raise a <a class="reference internal" href="../builtins/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception.
|
||
Any further awaitables returned by subsequent calls to the asynchronous
|
||
generator will raise a <a class="reference internal" href="../builtins/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> exception. If the
|
||
asynchronous generator yields a value, a <a class="reference internal" href="../builtins/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised
|
||
by the awaitable. If the asynchronous generator raises any other exception,
|
||
it is propagated to the caller of the awaitable. If the asynchronous
|
||
generator has already exited due to an exception or normal exit, then
|
||
further calls to <code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code> will return an awaitable that does nothing.</p>
|
||
</dd></dl>
|
||
|
||
</section>
|
||
</section>
|
||
</section>
|
||
<section id="primaries">
|
||
<span id="id7"></span><h2><span class="section-number">6.3. </span>Primaries<a class="headerlink" href="#primaries" title="Link to this heading">¶</a></h2>
|
||
<p id="index-42">Primaries represent the most tightly bound operations of the language. Their
|
||
syntax is:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-primary">primary</strong>: <a class="reference internal" href="#grammar-token-python-grammar-atom"><code class="xref docutils literal notranslate"><span class="pre">atom</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-attributeref"><code class="xref docutils literal notranslate"><span class="pre">attributeref</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-subscription"><code class="xref docutils literal notranslate"><span class="pre">subscription</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-call"><code class="xref docutils literal notranslate"><span class="pre">call</span></code></a>
|
||
</pre>
|
||
<section id="attribute-references">
|
||
<span id="id8"></span><h3><span class="section-number">6.3.1. </span>Attribute references<a class="headerlink" href="#attribute-references" title="Link to this heading">¶</a></h3>
|
||
<p id="index-43">An attribute reference is a primary followed by a period and a name:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-attributeref">attributeref</strong>: <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> <span class="sx">"."</span> <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
|
||
</pre>
|
||
<p id="index-44">The primary must evaluate to an object of a type that supports attribute
|
||
references, which most objects do. This object is then asked to produce the
|
||
attribute whose name is the identifier. The type and value produced is
|
||
determined by the object. Multiple evaluations of the same attribute
|
||
reference may yield different objects.</p>
|
||
<p>This production can be customized by overriding the
|
||
<a class="reference internal" href="datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> method or the <a class="reference internal" href="datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a>
|
||
method. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code> method is called first and either
|
||
returns a value or raises <a class="reference internal" href="../builtins/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> if the attribute is not
|
||
available.</p>
|
||
<p>If an <a class="reference internal" href="../builtins/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> is raised and the object has a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code>
|
||
method, that method is called as a fallback.</p>
|
||
</section>
|
||
<section id="subscriptions-and-slicings">
|
||
<span id="subscriptions"></span><h3><span class="section-number">6.3.2. </span>Subscriptions and slicings<a class="headerlink" href="#subscriptions-and-slicings" title="Link to this heading">¶</a></h3>
|
||
<p id="index-46"><span id="index-45"></span>The <em class="dfn">subscription</em> syntax is usually used for selecting an element from a
|
||
<a class="reference internal" href="datamodel.html#sequence-types"><span class="std std-ref">container</span></a> – for example, to get a value from
|
||
a <a class="reference internal" href="../builtins/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">digits_by_name</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'one'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">'two'</span><span class="p">:</span> <span class="mi">2</span><span class="p">}</span>
|
||
<span class="gp">>>> </span><span class="n">digits_by_name</span><span class="p">[</span><span class="s1">'two'</span><span class="p">]</span> <span class="c1"># Subscripting a dictionary using the key 'two'</span>
|
||
<span class="go">2</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>In the subscription syntax, the object being subscribed – a
|
||
<a class="reference internal" href="#primaries"><span class="std std-ref">primary</span></a> – is followed by a <em class="dfn">subscript</em> in
|
||
square brackets.
|
||
In the simplest case, the subscript is a single expression.</p>
|
||
<p>Depending on the type of the object being subscribed, the subscript is
|
||
sometimes called a <a class="reference internal" href="../glossary.html#term-key"><span class="xref std std-term">key</span></a> (for mappings), <a class="reference internal" href="../glossary.html#term-index"><span class="xref std std-term">index</span></a> (for sequences),
|
||
or <em>type argument</em> (for <a class="reference internal" href="../glossary.html#term-generic-type"><span class="xref std std-term">generic types</span></a>).
|
||
Syntactically, these are all equivalent:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">colors</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'red'</span><span class="p">,</span> <span class="s1">'blue'</span><span class="p">,</span> <span class="s1">'green'</span><span class="p">,</span> <span class="s1">'black'</span><span class="p">]</span>
|
||
<span class="gp">>>> </span><span class="n">colors</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span> <span class="c1"># Subscripting a list using the index 3</span>
|
||
<span class="go">'black'</span>
|
||
|
||
<span class="gp">>>> </span><span class="nb">list</span><span class="p">[</span><span class="nb">str</span><span class="p">]</span> <span class="c1"># Parameterizing the list type using the type argument str</span>
|
||
<span class="go">list[str]</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>At runtime, the interpreter will evaluate the primary and
|
||
the subscript, and call the primary’s <a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> or
|
||
<a class="reference internal" href="datamodel.html#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a> <a class="reference internal" href="../glossary.html#term-special-method"><span class="xref std std-term">special method</span></a> with the subscript
|
||
as argument.
|
||
For more details on which of these methods is called, see
|
||
<a class="reference internal" href="datamodel.html#classgetitem-versus-getitem"><span class="std std-ref">__class_getitem__ versus __getitem__</span></a>.</p>
|
||
<p>To show how subscription works, we can define a custom object that
|
||
implements <a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> and prints out the value of
|
||
the subscript:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span><span class="w"> </span><span class="nc">SubscriptionDemo</span><span class="p">:</span>
|
||
<span class="gp">... </span> <span class="k">def</span><span class="w"> </span><span class="fm">__getitem__</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="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'subscripted with: </span><span class="si">{</span><span class="n">key</span><span class="si">!r}</span><span class="s1">'</span><span class="p">)</span>
|
||
<span class="gp">...</span>
|
||
<span class="gp">>>> </span><span class="n">demo</span> <span class="o">=</span> <span class="n">SubscriptionDemo</span><span class="p">()</span>
|
||
<span class="gp">>>> </span><span class="n">demo</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
|
||
<span class="go">subscripted with: 1</span>
|
||
<span class="gp">>>> </span><span class="n">demo</span><span class="p">[</span><span class="s1">'a'</span> <span class="o">*</span> <span class="mi">3</span><span class="p">]</span>
|
||
<span class="go">subscripted with: 'aaa'</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>See <a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> documentation for how built-in types handle
|
||
subscription.</p>
|
||
<p>Subscriptions may also be used as targets in <a class="reference internal" href="simple_stmts.html#assignment"><span class="std std-ref">assignment</span></a> or
|
||
<a class="reference internal" href="simple_stmts.html#del"><span class="std std-ref">deletion</span></a> statements.
|
||
In these cases, the interpreter will call the subscripted object’s
|
||
<a class="reference internal" href="datamodel.html#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a> or <a class="reference internal" href="datamodel.html#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a>
|
||
<a class="reference internal" href="../glossary.html#term-special-method"><span class="xref std std-term">special method</span></a>, respectively, instead of <a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>.</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">colors</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'red'</span><span class="p">,</span> <span class="s1">'blue'</span><span class="p">,</span> <span class="s1">'green'</span><span class="p">,</span> <span class="s1">'black'</span><span class="p">]</span>
|
||
<span class="gp">>>> </span><span class="n">colors</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'white'</span> <span class="c1"># Setting item at index</span>
|
||
<span class="gp">>>> </span><span class="n">colors</span>
|
||
<span class="go">['red', 'blue', 'green', 'white']</span>
|
||
<span class="gp">>>> </span><span class="k">del</span> <span class="n">colors</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span> <span class="c1"># Deleting item at index 3</span>
|
||
<span class="gp">>>> </span><span class="n">colors</span>
|
||
<span class="go">['red', 'blue', 'green']</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>All advanced forms of <em>subscript</em> documented in the following sections
|
||
are also usable for assignment and deletion.</p>
|
||
<section id="slicings">
|
||
<span id="index-48"></span><span id="index-47"></span><span id="id9"></span><h4><span class="section-number">6.3.2.1. </span>Slicings<a class="headerlink" href="#slicings" title="Link to this heading">¶</a></h4>
|
||
<p>A more advanced form of subscription, <em class="dfn">slicing</em>, is commonly used
|
||
to extract a portion of a <a class="reference internal" href="datamodel.html#datamodel-sequences"><span class="std std-ref">sequence</span></a>.
|
||
In this form, the subscript is a <a class="reference internal" href="../glossary.html#term-slice"><span class="xref std std-term">slice</span></a>: up to three
|
||
expressions separated by colons.
|
||
Any of the expressions may be omitted, but a slice must contain at least one
|
||
colon:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">number_names</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'zero'</span><span class="p">,</span> <span class="s1">'one'</span><span class="p">,</span> <span class="s1">'two'</span><span class="p">,</span> <span class="s1">'three'</span><span class="p">,</span> <span class="s1">'four'</span><span class="p">,</span> <span class="s1">'five'</span><span class="p">]</span>
|
||
<span class="gp">>>> </span><span class="n">number_names</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">3</span><span class="p">]</span>
|
||
<span class="go">['one', 'two']</span>
|
||
<span class="gp">>>> </span><span class="n">number_names</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
|
||
<span class="go">['one', 'two', 'three', 'four', 'five']</span>
|
||
<span class="gp">>>> </span><span class="n">number_names</span><span class="p">[:</span><span class="mi">3</span><span class="p">]</span>
|
||
<span class="go">['zero', 'one', 'two']</span>
|
||
<span class="gp">>>> </span><span class="n">number_names</span><span class="p">[:]</span>
|
||
<span class="go">['zero', 'one', 'two', 'three', 'four', 'five']</span>
|
||
<span class="gp">>>> </span><span class="n">number_names</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
|
||
<span class="go">['zero', 'two', 'four']</span>
|
||
<span class="gp">>>> </span><span class="n">number_names</span><span class="p">[:</span><span class="o">-</span><span class="mi">3</span><span class="p">]</span>
|
||
<span class="go">['zero', 'one', 'two']</span>
|
||
<span class="gp">>>> </span><span class="k">del</span> <span class="n">number_names</span><span class="p">[</span><span class="mi">4</span><span class="p">:]</span>
|
||
<span class="gp">>>> </span><span class="n">number_names</span>
|
||
<span class="go">['zero', 'one', 'two', 'three']</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>When a slice is evaluated, the interpreter constructs a <a class="reference internal" href="../builtins/functions.html#slice" title="slice"><code class="xref py py-class docutils literal notranslate"><span class="pre">slice</span></code></a> object
|
||
whose <a class="reference internal" href="../builtins/functions.html#slice.start" title="slice.start"><code class="xref py py-attr docutils literal notranslate"><span class="pre">start</span></code></a>, <a class="reference internal" href="../builtins/functions.html#slice.stop" title="slice.stop"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stop</span></code></a> and
|
||
<a class="reference internal" href="../builtins/functions.html#slice.step" title="slice.step"><code class="xref py py-attr docutils literal notranslate"><span class="pre">step</span></code></a> attributes, respectively, are the results of the
|
||
expressions between the colons.
|
||
Any missing expression evaluates to <a class="reference internal" href="../builtins/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.
|
||
This <code class="xref py py-class docutils literal notranslate"><span class="pre">slice</span></code> object is then passed to the <a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>
|
||
or <a class="reference internal" href="datamodel.html#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a> <a class="reference internal" href="../glossary.html#term-special-method"><span class="xref std std-term">special method</span></a>, as above.</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># continuing with the SubscriptionDemo instance defined above:</span>
|
||
<span class="o">>>></span> <span class="n">demo</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">3</span><span class="p">]</span>
|
||
<span class="n">subscripted</span> <span class="k">with</span><span class="p">:</span> <span class="nb">slice</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="kc">None</span><span class="p">)</span>
|
||
<span class="o">>>></span> <span class="n">demo</span><span class="p">[::</span><span class="s1">'spam'</span><span class="p">]</span>
|
||
<span class="n">subscripted</span> <span class="k">with</span><span class="p">:</span> <span class="nb">slice</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="s1">'spam'</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
</section>
|
||
<section id="comma-separated-subscripts">
|
||
<h4><span class="section-number">6.3.2.2. </span>Comma-separated subscripts<a class="headerlink" href="#comma-separated-subscripts" title="Link to this heading">¶</a></h4>
|
||
<p>The subscript can also be given as two or more comma-separated expressions
|
||
or slices:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># continuing with the SubscriptionDemo instance defined above:</span>
|
||
<span class="o">>>></span> <span class="n">demo</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
|
||
<span class="n">subscripted</span> <span class="k">with</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="o">>>></span> <span class="n">demo</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
|
||
<span class="n">subscripted</span> <span class="k">with</span><span class="p">:</span> <span class="p">(</span><span class="nb">slice</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="kc">None</span><span class="p">),</span> <span class="mi">3</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>This form is commonly used with numerical libraries for slicing
|
||
multi-dimensional data.
|
||
In this case, the interpreter constructs a <a class="reference internal" href="../builtins/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> of the results of the
|
||
expressions or slices, and passes this tuple to the <a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>
|
||
or <a class="reference internal" href="datamodel.html#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a> <a class="reference internal" href="../glossary.html#term-special-method"><span class="xref std std-term">special method</span></a>, as above.</p>
|
||
<p>The subscript may also be given as a single expression or slice followed
|
||
by a comma, to specify a one-element tuple:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">demo</span><span class="p">[</span><span class="s1">'spam'</span><span class="p">,]</span>
|
||
<span class="go">subscripted with: ('spam',)</span>
|
||
</pre></div>
|
||
</div>
|
||
</section>
|
||
<section id="starred-subscriptions">
|
||
<h4><span class="section-number">6.3.2.3. </span>“Starred” subscriptions<a class="headerlink" href="#starred-subscriptions" title="Link to this heading">¶</a></h4>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">Added in version 3.11: </span>Expressions in <em>tuple_slices</em> may be starred. See <span class="target" id="index-49"></span><a class="pep reference external" href="https://peps.python.org/pep-0646/"><strong>PEP 646</strong></a>.</p>
|
||
</div>
|
||
<p>The subscript can also contain a starred expression.
|
||
In this case, the interpreter unpacks the result into a tuple, and passes
|
||
this tuple to <a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> or <a class="reference internal" href="datamodel.html#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># continuing with the SubscriptionDemo instance defined above:</span>
|
||
<span class="o">>>></span> <span class="n">demo</span><span class="p">[</span><span class="o">*</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)]</span>
|
||
<span class="n">subscripted</span> <span class="k">with</span><span class="p">:</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">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="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Starred expressions may be combined with comma-separated expressions
|
||
and slices:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">demo</span><span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="o">*</span><span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">),</span> <span class="s1">'c'</span><span class="p">]</span>
|
||
<span class="go">subscripted with: ('a', 'b', 0, 1, 2, 'c')</span>
|
||
</pre></div>
|
||
</div>
|
||
</section>
|
||
<section id="formal-subscription-grammar">
|
||
<h4><span class="section-number">6.3.2.4. </span>Formal subscription grammar<a class="headerlink" href="#formal-subscription-grammar" title="Link to this heading">¶</a></h4>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-subscription">subscription</strong>: <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> <span class="sx">'['</span> <a class="reference internal" href="#grammar-token-python-grammar-subscript"><code class="xref docutils literal notranslate"><span class="pre">subscript</span></code></a> <span class="sx">']'</span>
|
||
<strong id="grammar-token-python-grammar-subscript">subscript</strong>: <a class="reference internal" href="#grammar-token-python-grammar-single_subscript"><code class="xref docutils literal notranslate"><span class="pre">single_subscript</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-tuple_subscript"><code class="xref docutils literal notranslate"><span class="pre">tuple_subscript</span></code></a>
|
||
<strong id="grammar-token-python-grammar-single_subscript">single_subscript</strong>: <a class="reference internal" href="#grammar-token-python-grammar-proper_slice"><code class="xref docutils literal notranslate"><span class="pre">proper_slice</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-assignment_expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a>
|
||
<strong id="grammar-token-python-grammar-proper_slice">proper_slice</strong>: [<a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>] <span class="sx">":"</span> [<a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>] [ <span class="sx">":"</span> [<a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>] ]
|
||
<strong id="grammar-token-python-grammar-tuple_subscript">tuple_subscript</strong>: <span class="sx">','</span>.(<a class="reference internal" href="#grammar-token-python-grammar-single_subscript"><code class="xref docutils literal notranslate"><span class="pre">single_subscript</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-starred_expression"><code class="xref docutils literal notranslate"><span class="pre">starred_expression</span></code></a>)+ [<span class="sx">','</span>]
|
||
</pre>
|
||
<p>Recall that the <code class="docutils literal notranslate"><span class="pre">|</span></code> operator <a class="reference internal" href="introduction.html#notation"><span class="std std-ref">denotes ordered choice</span></a>.
|
||
Specifically, in <code class="xref std std-token docutils literal notranslate"><span class="pre">subscript</span></code>, if both alternatives would match, the
|
||
first (<code class="xref std std-token docutils literal notranslate"><span class="pre">single_subscript</span></code>) has priority.</p>
|
||
</section>
|
||
</section>
|
||
<section id="calls">
|
||
<span id="index-50"></span><span id="id10"></span><h3><span class="section-number">6.3.3. </span>Calls<a class="headerlink" href="#calls" title="Link to this heading">¶</a></h3>
|
||
<p>A call calls a callable object (e.g., a <a class="reference internal" href="../glossary.html#term-function"><span class="xref std std-term">function</span></a>) with a possibly empty
|
||
series of <a class="reference internal" href="../glossary.html#term-argument"><span class="xref std std-term">arguments</span></a>:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-call">call</strong>: <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> <span class="sx">"("</span> [<a class="reference internal" href="#grammar-token-python-grammar-argument_list"><code class="xref docutils literal notranslate"><span class="pre">argument_list</span></code></a> [<span class="sx">","</span>] | <a class="reference internal" href="#grammar-token-python-grammar-comprehension"><code class="xref docutils literal notranslate"><span class="pre">comprehension</span></code></a>] <span class="sx">")"</span>
|
||
<strong id="grammar-token-python-grammar-argument_list">argument_list</strong>: <a class="reference internal" href="#grammar-token-python-grammar-positional_arguments"><code class="xref docutils literal notranslate"><span class="pre">positional_arguments</span></code></a> [<span class="sx">","</span> <a class="reference internal" href="#grammar-token-python-grammar-starred_and_keywords"><code class="xref docutils literal notranslate"><span class="pre">starred_and_keywords</span></code></a>]
|
||
[<span class="sx">","</span> <a class="reference internal" href="#grammar-token-python-grammar-keywords_arguments"><code class="xref docutils literal notranslate"><span class="pre">keywords_arguments</span></code></a>]
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-starred_and_keywords"><code class="xref docutils literal notranslate"><span class="pre">starred_and_keywords</span></code></a> [<span class="sx">","</span> <a class="reference internal" href="#grammar-token-python-grammar-keywords_arguments"><code class="xref docutils literal notranslate"><span class="pre">keywords_arguments</span></code></a>]
|
||
| <a class="reference internal" href="#grammar-token-python-grammar-keywords_arguments"><code class="xref docutils literal notranslate"><span class="pre">keywords_arguments</span></code></a>
|
||
<strong id="grammar-token-python-grammar-positional_arguments">positional_arguments</strong>: <a class="reference internal" href="#grammar-token-python-grammar-positional_item"><code class="xref docutils literal notranslate"><span class="pre">positional_item</span></code></a> (<span class="sx">","</span> <a class="reference internal" href="#grammar-token-python-grammar-positional_item"><code class="xref docutils literal notranslate"><span class="pre">positional_item</span></code></a>)*
|
||
<strong id="grammar-token-python-grammar-positional_item">positional_item</strong>: <a class="reference internal" href="#grammar-token-python-grammar-assignment_expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> | <span class="sx">"*"</span> <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
|
||
<strong id="grammar-token-python-grammar-starred_and_keywords">starred_and_keywords</strong>: (<span class="sx">"*"</span> <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a>)
|
||
(<span class="sx">","</span> <span class="sx">"*"</span> <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> | <span class="sx">","</span> <a class="reference internal" href="#grammar-token-python-grammar-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a>)*
|
||
<strong id="grammar-token-python-grammar-keywords_arguments">keywords_arguments</strong>: (<a class="reference internal" href="#grammar-token-python-grammar-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a> | <span class="sx">"**"</span> <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>)
|
||
(<span class="sx">","</span> <a class="reference internal" href="#grammar-token-python-grammar-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a> | <span class="sx">","</span> <span class="sx">"**"</span> <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>)*
|
||
<strong id="grammar-token-python-grammar-keyword_item">keyword_item</strong>: <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> <span class="sx">"="</span> <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
|
||
</pre>
|
||
<p>An optional trailing comma may be present after the positional and keyword arguments
|
||
but does not affect the semantics.</p>
|
||
<p id="index-51">The primary must evaluate to a callable object (user-defined functions, built-in
|
||
functions, methods of built-in objects, class objects, methods of class
|
||
instances, and all objects having a <a class="reference internal" href="datamodel.html#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> method are callable). All
|
||
argument expressions are evaluated before the call is attempted. Please refer
|
||
to section <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a> for the syntax of formal <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameter</span></a> lists.</p>
|
||
<p>If keyword arguments are present, they are first converted to positional
|
||
arguments, as follows. First, a list of unfilled slots is created for the
|
||
formal parameters. If there are N positional arguments, they are placed in the
|
||
first N slots. Next, for each keyword argument, the identifier is used to
|
||
determine the corresponding slot (if the identifier is the same as the first
|
||
formal parameter name, the first slot is used, and so on). If the slot is
|
||
already filled, a <a class="reference internal" href="../builtins/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised. Otherwise, the
|
||
argument is placed in the slot, filling it (even if the expression is
|
||
<code class="docutils literal notranslate"><span class="pre">None</span></code>, it fills the slot). When all arguments have been processed, the slots
|
||
that are still unfilled are filled with the corresponding default value from the
|
||
function definition. (Default values are calculated, once, when the function is
|
||
defined; thus, a mutable object such as a list or dictionary used as default
|
||
value will be shared by all calls that don’t specify an argument value for the
|
||
corresponding slot; this should usually be avoided.) If there are any unfilled
|
||
slots for which no default value is specified, a <code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code> exception is
|
||
raised. Otherwise, the list of filled slots is used as the argument list for
|
||
the call.</p>
|
||
<div class="impl-detail compound">
|
||
<p><strong>CPython implementation detail:</strong> An implementation may provide built-in functions whose positional parameters
|
||
do not have names, even if they are ‘named’ for the purpose of documentation,
|
||
and which therefore cannot be supplied by keyword. In CPython, this is the
|
||
case for functions implemented in C that use <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> to
|
||
parse their arguments.</p>
|
||
</div>
|
||
<p>If there are more positional arguments than there are formal parameter slots, a
|
||
<a class="reference internal" href="../builtins/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised, unless a formal parameter using the syntax
|
||
<code class="docutils literal notranslate"><span class="pre">*identifier</span></code> is present; in this case, that formal parameter receives a tuple
|
||
containing the excess positional arguments (or an empty tuple if there were no
|
||
excess positional arguments).</p>
|
||
<p>If any keyword argument does not correspond to a formal parameter name, a
|
||
<a class="reference internal" href="../builtins/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised, unless a formal parameter using the syntax
|
||
<code class="docutils literal notranslate"><span class="pre">**identifier</span></code> is present; in this case, that formal parameter receives a
|
||
dictionary containing the excess keyword arguments (using the keywords as keys
|
||
and the argument values as corresponding values), or a (new) empty dictionary if
|
||
there were no excess keyword arguments.</p>
|
||
<p id="index-52">If the syntax <code class="docutils literal notranslate"><span class="pre">*expression</span></code> appears in the function call, <code class="docutils literal notranslate"><span class="pre">expression</span></code> must
|
||
evaluate to an <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a>. Elements from these iterables are
|
||
treated as if they were additional positional arguments. For the call
|
||
<code class="docutils literal notranslate"><span class="pre">f(x1,</span> <span class="pre">x2,</span> <span class="pre">*y,</span> <span class="pre">x3,</span> <span class="pre">x4)</span></code>, if <em>y</em> evaluates to a sequence <em>y1</em>, …, <em>yM</em>,
|
||
this is equivalent to a call with M+4 positional arguments <em>x1</em>, <em>x2</em>,
|
||
<em>y1</em>, …, <em>yM</em>, <em>x3</em>, <em>x4</em>.</p>
|
||
<p>A consequence of this is that although the <code class="docutils literal notranslate"><span class="pre">*expression</span></code> syntax may appear
|
||
<em>after</em> explicit keyword arguments, it is processed <em>before</em> the
|
||
keyword arguments (and any <code class="docutils literal notranslate"><span class="pre">**expression</span></code> arguments – see below). So:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
|
||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
|
||
<span class="gp">...</span>
|
||
<span class="gp">>>> </span><span class="n">f</span><span class="p">(</span><span class="n">b</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="o">*</span><span class="p">(</span><span class="mi">2</span><span class="p">,))</span>
|
||
<span class="go">2 1</span>
|
||
<span class="gp">>>> </span><span class="n">f</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="o">*</span><span class="p">(</span><span class="mi">2</span><span class="p">,))</span>
|
||
<span class="gt">Traceback (most recent call last):</span>
|
||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
|
||
<span class="gr">TypeError</span>: <span class="n">f() got multiple values for keyword argument 'a'</span>
|
||
<span class="gp">>>> </span><span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="o">*</span><span class="p">(</span><span class="mi">2</span><span class="p">,))</span>
|
||
<span class="go">1 2</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>It is unusual for both keyword arguments and the <code class="docutils literal notranslate"><span class="pre">*expression</span></code> syntax to be
|
||
used in the same call, so in practice this confusion does not often arise.</p>
|
||
<p id="index-53">If the syntax <code class="docutils literal notranslate"><span class="pre">**expression</span></code> appears in the function call, <code class="docutils literal notranslate"><span class="pre">expression</span></code> must
|
||
evaluate to a <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a>, the contents of which are treated as
|
||
additional keyword arguments. If a parameter matching a key has already been
|
||
given a value (by an explicit keyword argument, or from another unpacking),
|
||
a <a class="reference internal" href="../builtins/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised.</p>
|
||
<p>When <code class="docutils literal notranslate"><span class="pre">**expression</span></code> is used, each key in this mapping must be
|
||
a string.
|
||
Each value from the mapping is assigned to the first formal parameter
|
||
eligible for keyword assignment whose name is equal to the key.
|
||
A key need not be a Python identifier (e.g. <code class="docutils literal notranslate"><span class="pre">"max-temp</span> <span class="pre">°F"</span></code> is acceptable,
|
||
although it will not match any formal parameter that could be declared).
|
||
If there is no match to a formal parameter
|
||
the key-value pair is collected by the <code class="docutils literal notranslate"><span class="pre">**</span></code> parameter, if there is one,
|
||
or if there is not, a <a class="reference internal" href="../builtins/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised.</p>
|
||
<p>Formal parameters using the syntax <code class="docutils literal notranslate"><span class="pre">*identifier</span></code> or <code class="docutils literal notranslate"><span class="pre">**identifier</span></code> cannot be
|
||
used as positional argument slots or as keyword argument names.</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.5: </span>Function calls accept any number of <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">**</span></code> unpackings,
|
||
positional arguments may follow iterable unpackings (<code class="docutils literal notranslate"><span class="pre">*</span></code>),
|
||
and keyword arguments may follow dictionary unpackings (<code class="docutils literal notranslate"><span class="pre">**</span></code>).
|
||
Originally proposed by <span class="target" id="index-54"></span><a class="pep reference external" href="https://peps.python.org/pep-0448/"><strong>PEP 448</strong></a>.</p>
|
||
</div>
|
||
<p>A call always returns some value, possibly <code class="docutils literal notranslate"><span class="pre">None</span></code>, unless it raises an
|
||
exception. How this value is computed depends on the type of the callable
|
||
object.</p>
|
||
<p>If it is—</p>
|
||
<dl>
|
||
<dt>a user-defined function:</dt><dd><p id="index-55">The code block for the function is executed, passing it the argument list. The
|
||
first thing the code block will do is bind the formal parameters to the
|
||
arguments; this is described in section <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a>. When the code block
|
||
executes a <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement, this specifies the return value of the
|
||
function call. If execution reaches the end of the code block without
|
||
executing a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code> statement, the return value is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
|
||
</dd>
|
||
<dt>a built-in function or method:</dt><dd><p id="index-56">The result is up to the interpreter; see <a class="reference internal" href="../builtins/functions.html#built-in-funcs"><span class="std std-ref">Built-in functions</span></a> for the
|
||
descriptions of built-in functions and methods.</p>
|
||
</dd>
|
||
<dt>a class object:</dt><dd><p id="index-57">A new instance of that class is returned.</p>
|
||
</dd>
|
||
<dt>a class instance method:</dt><dd><p id="index-58">The corresponding user-defined function is called, with an argument list that is
|
||
one longer than the argument list of the call: the instance becomes the first
|
||
argument.</p>
|
||
</dd>
|
||
<dt>a class instance:</dt><dd><p id="index-59">The class must define a <a class="reference internal" href="datamodel.html#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> method; the effect is then the same as
|
||
if that method was called.</p>
|
||
</dd>
|
||
</dl>
|
||
</section>
|
||
</section>
|
||
<section id="await-expression">
|
||
<span id="await"></span><span id="index-60"></span><h2><span class="section-number">6.4. </span>Await expression<a class="headerlink" href="#await-expression" title="Link to this heading">¶</a></h2>
|
||
<p>Suspend the execution of <a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">coroutine</span></a> on an <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> object.
|
||
Can only be used inside a <a class="reference internal" href="../glossary.html#term-coroutine-function"><span class="xref std std-term">coroutine function</span></a>.</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-await_expr">await_expr</strong>: <span class="sx">"await"</span> <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a>
|
||
</pre>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">Added in version 3.5.</span></p>
|
||
</div>
|
||
</section>
|
||
<section id="the-power-operator">
|
||
<span id="power"></span><h2><span class="section-number">6.5. </span>The power operator<a class="headerlink" href="#the-power-operator" title="Link to this heading">¶</a></h2>
|
||
<p id="index-61">The power operator binds more tightly than unary operators on its left; it binds
|
||
less tightly than unary operators on its right. The syntax is:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-power">power</strong>: (<a class="reference internal" href="#grammar-token-python-grammar-await_expr"><code class="xref docutils literal notranslate"><span class="pre">await_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a>) [<span class="sx">"**"</span> <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a>]
|
||
</pre>
|
||
<p>Thus, in an unparenthesized sequence of power and unary operators, the operators
|
||
are evaluated from right to left (this does not constrain the evaluation order
|
||
for the operands): <code class="docutils literal notranslate"><span class="pre">-1**2</span></code> results in <code class="docutils literal notranslate"><span class="pre">-1</span></code>.</p>
|
||
<p>The power operator has the same semantics as the built-in <a class="reference internal" href="../builtins/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a> function,
|
||
when called with two arguments: it yields its left argument raised to the power
|
||
of its right argument.
|
||
Numeric arguments are first <a class="reference internal" href="../builtins/stdtypes.html#stdtypes-mixed-arithmetic"><span class="std std-ref">converted to a common type</span></a>,
|
||
and the result is of that type.</p>
|
||
<p>For int operands, the result has the same type as the operands unless the second
|
||
argument is negative; in that case, all arguments are converted to float and a
|
||
float result is delivered. For example, <code class="docutils literal notranslate"><span class="pre">10**2</span></code> returns <code class="docutils literal notranslate"><span class="pre">100</span></code>, but
|
||
<code class="docutils literal notranslate"><span class="pre">10**-2</span></code> returns <code class="docutils literal notranslate"><span class="pre">0.01</span></code>.</p>
|
||
<p>Raising <code class="docutils literal notranslate"><span class="pre">0.0</span></code> to a negative power results in a <a class="reference internal" href="../builtins/exceptions.html#ZeroDivisionError" title="ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a>.
|
||
Raising a negative number to a fractional power results in a <a class="reference internal" href="../builtins/functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a>
|
||
number. (In earlier versions it raised a <a class="reference internal" href="../builtins/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.)</p>
|
||
<p>This operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__pow__" title="object.__pow__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__pow__()</span></code></a> and
|
||
<a class="reference internal" href="datamodel.html#object.__rpow__" title="object.__rpow__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rpow__()</span></code></a> methods.</p>
|
||
</section>
|
||
<section id="unary-arithmetic-and-bitwise-operations">
|
||
<span id="unary"></span><h2><span class="section-number">6.6. </span>Unary arithmetic and bitwise operations<a class="headerlink" href="#unary-arithmetic-and-bitwise-operations" title="Link to this heading">¶</a></h2>
|
||
<p id="index-62">All unary arithmetic and bitwise operations have the same priority:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-u_expr">u_expr</strong>: <a class="reference internal" href="#grammar-token-python-grammar-power"><code class="xref docutils literal notranslate"><span class="pre">power</span></code></a> | <span class="sx">"-"</span> <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | <span class="sx">"+"</span> <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | <span class="sx">"~"</span> <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a>
|
||
</pre>
|
||
<p id="index-63">The unary <code class="docutils literal notranslate"><span class="pre">-</span></code> (minus) operator yields the negation of its numeric argument; the
|
||
operation can be overridden with the <a class="reference internal" href="datamodel.html#object.__neg__" title="object.__neg__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__neg__()</span></code></a> special method.</p>
|
||
<p id="index-64">The unary <code class="docutils literal notranslate"><span class="pre">+</span></code> (plus) operator yields its numeric argument unchanged; the
|
||
operation can be overridden with the <a class="reference internal" href="datamodel.html#object.__pos__" title="object.__pos__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__pos__()</span></code></a> special method.</p>
|
||
<p id="index-65">The unary <code class="docutils literal notranslate"><span class="pre">~</span></code> (invert) operator yields the bitwise inversion of its integer
|
||
argument. The bitwise inversion of <code class="docutils literal notranslate"><span class="pre">x</span></code> is defined as <code class="docutils literal notranslate"><span class="pre">-(x+1)</span></code>. It only
|
||
applies to integral numbers or to custom objects that override the
|
||
<a class="reference internal" href="datamodel.html#object.__invert__" title="object.__invert__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__invert__()</span></code></a> special method.</p>
|
||
<p id="index-66">In all three cases, if the argument does not have the proper type, a
|
||
<a class="reference internal" href="../builtins/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised.</p>
|
||
</section>
|
||
<section id="binary-arithmetic-operations">
|
||
<span id="binary"></span><h2><span class="section-number">6.7. </span>Binary arithmetic operations<a class="headerlink" href="#binary-arithmetic-operations" title="Link to this heading">¶</a></h2>
|
||
<p id="index-67">The binary arithmetic operations have the conventional priority levels. Note
|
||
that some of these operations also apply to certain non-numeric types. Apart
|
||
from the power operator, there are only two levels, one for multiplicative
|
||
operators and one for additive operators:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-m_expr">m_expr</strong>: <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> <span class="sx">"*"</span> <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> <span class="sx">"@"</span> <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> |
|
||
<a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> <span class="sx">"//"</span> <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> <span class="sx">"/"</span> <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> |
|
||
<a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> <span class="sx">"%"</span> <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a>
|
||
<strong id="grammar-token-python-grammar-a_expr">a_expr</strong>: <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a> <span class="sx">"+"</span> <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a> <span class="sx">"-"</span> <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a>
|
||
</pre>
|
||
<p id="index-68">The <code class="docutils literal notranslate"><span class="pre">*</span></code> (multiplication) operator yields the product of its arguments. The
|
||
arguments must either both be numbers, or one argument must be an integer and
|
||
the other must be a sequence. In the former case, the numbers are
|
||
<a class="reference internal" href="../builtins/stdtypes.html#stdtypes-mixed-arithmetic"><span class="std std-ref">converted to a common real type</span></a> and then
|
||
multiplied together. In the latter case, sequence repetition is performed;
|
||
a negative repetition factor yields an empty sequence.</p>
|
||
<p>This operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__mul__" title="object.__mul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__mul__()</span></code></a> and
|
||
<a class="reference internal" href="datamodel.html#object.__rmul__" title="object.__rmul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rmul__()</span></code></a> methods.</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.14: </span>If only one operand is a complex number, the other operand is converted
|
||
to a floating-point number.</p>
|
||
</div>
|
||
<p id="index-69">The <code class="docutils literal notranslate"><span class="pre">@</span></code> (at) operator is intended to be used for matrix multiplication. No
|
||
builtin Python types implement this operator.</p>
|
||
<p>This operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__matmul__" title="object.__matmul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__matmul__()</span></code></a> and
|
||
<a class="reference internal" href="datamodel.html#object.__rmatmul__" title="object.__rmatmul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rmatmul__()</span></code></a> methods.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">Added in version 3.5.</span></p>
|
||
</div>
|
||
<p id="index-70">The <code class="docutils literal notranslate"><span class="pre">/</span></code> (division) and <code class="docutils literal notranslate"><span class="pre">//</span></code> (floor division) operators yield the quotient of
|
||
their arguments. The numeric arguments are first
|
||
<a class="reference internal" href="../builtins/stdtypes.html#stdtypes-mixed-arithmetic"><span class="std std-ref">converted to a common type</span></a>.
|
||
Division of integers yields a float, while floor division of integers results in an
|
||
integer; the result is that of mathematical division with the ‘floor’ function
|
||
applied to the result. Division by zero raises the <a class="reference internal" href="../builtins/exceptions.html#ZeroDivisionError" title="ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a>
|
||
exception.</p>
|
||
<p>The division operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__truediv__" title="object.__truediv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__truediv__()</span></code></a>
|
||
and <a class="reference internal" href="datamodel.html#object.__rtruediv__" title="object.__rtruediv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rtruediv__()</span></code></a> methods.
|
||
The floor division operation can be customized using the special
|
||
<a class="reference internal" href="datamodel.html#object.__floordiv__" title="object.__floordiv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__floordiv__()</span></code></a> and <a class="reference internal" href="datamodel.html#object.__rfloordiv__" title="object.__rfloordiv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rfloordiv__()</span></code></a> methods.</p>
|
||
<p id="index-71">The <code class="docutils literal notranslate"><span class="pre">%</span></code> (modulo) operator yields the remainder from the division of the first
|
||
argument by the second. The numeric arguments are first
|
||
<a class="reference internal" href="../builtins/stdtypes.html#stdtypes-mixed-arithmetic"><span class="std std-ref">converted to a common type</span></a>.
|
||
A zero right argument raises the <a class="reference internal" href="../builtins/exceptions.html#ZeroDivisionError" title="ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a> exception. The
|
||
arguments may be floating-point numbers, e.g., <code class="docutils literal notranslate"><span class="pre">3.14%0.7</span></code> equals <code class="docutils literal notranslate"><span class="pre">0.34</span></code>
|
||
(since <code class="docutils literal notranslate"><span class="pre">3.14</span></code> equals <code class="docutils literal notranslate"><span class="pre">4*0.7</span> <span class="pre">+</span> <span class="pre">0.34</span></code>.) The modulo operator always yields a
|
||
result with the same sign as its second operand (or zero); the absolute value of
|
||
the result is strictly smaller than the absolute value of the second operand
|
||
<a class="footnote-reference brackets" href="#id22" id="id11" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>.</p>
|
||
<p>The floor division and modulo operators are connected by the following
|
||
identity: <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">(x//y)*y</span> <span class="pre">+</span> <span class="pre">(x%y)</span></code>. Floor division and modulo are also
|
||
connected with the built-in function <a class="reference internal" href="../builtins/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>: <code class="docutils literal notranslate"><span class="pre">divmod(x,</span> <span class="pre">y)</span> <span class="pre">==</span> <span class="pre">(x//y,</span>
|
||
<span class="pre">x%y)</span></code>. <a class="footnote-reference brackets" href="#id23" id="id12" role="doc-noteref"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a>.</p>
|
||
<p>In addition to performing the modulo operation on numbers, the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator is
|
||
also overloaded by string objects to perform old-style string formatting (also
|
||
known as interpolation). The syntax for string formatting is described in the
|
||
Python Library Reference, section <a class="reference internal" href="../builtins/stdtypes.html#old-string-formatting"><span class="std std-ref">printf-style String Formatting</span></a>.</p>
|
||
<p>The <em>modulo</em> operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__mod__" title="object.__mod__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__mod__()</span></code></a>
|
||
and <a class="reference internal" href="datamodel.html#object.__rmod__" title="object.__rmod__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rmod__()</span></code></a> methods.</p>
|
||
<p>The floor division operator, the modulo operator, and the <a class="reference internal" href="../builtins/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>
|
||
function are not defined for complex numbers. Instead, convert to a
|
||
floating-point number using the <a class="reference internal" href="../builtins/functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a> function if appropriate.</p>
|
||
<p id="index-72">The <code class="docutils literal notranslate"><span class="pre">+</span></code> (addition) operator yields the sum of its arguments. The arguments
|
||
must either both be numbers or both be sequences of the same type. In the
|
||
former case, the numbers are
|
||
<a class="reference internal" href="../builtins/stdtypes.html#stdtypes-mixed-arithmetic"><span class="std std-ref">converted to a common real type</span></a> and then
|
||
added together.
|
||
In the latter case, the sequences are concatenated.</p>
|
||
<p>This operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a> and
|
||
<a class="reference internal" href="datamodel.html#object.__radd__" title="object.__radd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__radd__()</span></code></a> methods.</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.14: </span>If only one operand is a complex number, the other operand is converted
|
||
to a floating-point number.</p>
|
||
</div>
|
||
<p id="index-73">The <code class="docutils literal notranslate"><span class="pre">-</span></code> (subtraction) operator yields the difference of its arguments.
|
||
The numeric arguments are first
|
||
<a class="reference internal" href="../builtins/stdtypes.html#stdtypes-mixed-arithmetic"><span class="std std-ref">converted to a common real type</span></a>.</p>
|
||
<p>This operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__sub__" title="object.__sub__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__sub__()</span></code></a> and
|
||
<a class="reference internal" href="datamodel.html#object.__rsub__" title="object.__rsub__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rsub__()</span></code></a> methods.</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.14: </span>If only one operand is a complex number, the other operand is converted
|
||
to a floating-point number.</p>
|
||
</div>
|
||
</section>
|
||
<section id="shifting-operations">
|
||
<span id="shifting"></span><h2><span class="section-number">6.8. </span>Shifting operations<a class="headerlink" href="#shifting-operations" title="Link to this heading">¶</a></h2>
|
||
<p id="index-74">The shifting operations have lower priority than the arithmetic operations:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-shift_expr">shift_expr</strong>: <a class="reference internal" href="#grammar-token-python-grammar-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-shift_expr"><code class="xref docutils literal notranslate"><span class="pre">shift_expr</span></code></a> (<span class="sx">"<<"</span> | <span class="sx">">>"</span>) <a class="reference internal" href="#grammar-token-python-grammar-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a>
|
||
</pre>
|
||
<p>These operators accept integers as arguments. They shift the first argument to
|
||
the left or right by the number of bits given by the second argument.</p>
|
||
<p>The left shift operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__lshift__" title="object.__lshift__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lshift__()</span></code></a>
|
||
and <a class="reference internal" href="datamodel.html#object.__rlshift__" title="object.__rlshift__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rlshift__()</span></code></a> methods.
|
||
The right shift operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__rshift__" title="object.__rshift__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rshift__()</span></code></a>
|
||
and <a class="reference internal" href="datamodel.html#object.__rrshift__" title="object.__rrshift__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rrshift__()</span></code></a> methods.</p>
|
||
<p id="index-75">A right shift by <em>n</em> bits is defined as floor division by <code class="docutils literal notranslate"><span class="pre">pow(2,n)</span></code>. A left
|
||
shift by <em>n</em> bits is defined as multiplication with <code class="docutils literal notranslate"><span class="pre">pow(2,n)</span></code>.</p>
|
||
</section>
|
||
<section id="binary-bitwise-operations">
|
||
<span id="bitwise"></span><h2><span class="section-number">6.9. </span>Binary bitwise operations<a class="headerlink" href="#binary-bitwise-operations" title="Link to this heading">¶</a></h2>
|
||
<p id="index-76">Each of the three bitwise operations has a different priority level:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-and_expr">and_expr</strong>: <a class="reference internal" href="#grammar-token-python-grammar-shift_expr"><code class="xref docutils literal notranslate"><span class="pre">shift_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-and_expr"><code class="xref docutils literal notranslate"><span class="pre">and_expr</span></code></a> <span class="sx">"&"</span> <a class="reference internal" href="#grammar-token-python-grammar-shift_expr"><code class="xref docutils literal notranslate"><span class="pre">shift_expr</span></code></a>
|
||
<strong id="grammar-token-python-grammar-xor_expr">xor_expr</strong>: <a class="reference internal" href="#grammar-token-python-grammar-and_expr"><code class="xref docutils literal notranslate"><span class="pre">and_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-xor_expr"><code class="xref docutils literal notranslate"><span class="pre">xor_expr</span></code></a> <span class="sx">"^"</span> <a class="reference internal" href="#grammar-token-python-grammar-and_expr"><code class="xref docutils literal notranslate"><span class="pre">and_expr</span></code></a>
|
||
<strong id="grammar-token-python-grammar-or_expr">or_expr</strong>: <a class="reference internal" href="#grammar-token-python-grammar-xor_expr"><code class="xref docutils literal notranslate"><span class="pre">xor_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a> <span class="sx">"|"</span> <a class="reference internal" href="#grammar-token-python-grammar-xor_expr"><code class="xref docutils literal notranslate"><span class="pre">xor_expr</span></code></a>
|
||
</pre>
|
||
<p id="index-77">The <code class="docutils literal notranslate"><span class="pre">&</span></code> operator yields the bitwise AND of its arguments, which must be
|
||
integers or one of them must be a custom object overriding <a class="reference internal" href="datamodel.html#object.__and__" title="object.__and__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__and__()</span></code></a> or
|
||
<a class="reference internal" href="datamodel.html#object.__rand__" title="object.__rand__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rand__()</span></code></a> special methods.</p>
|
||
<p id="index-78">The <code class="docutils literal notranslate"><span class="pre">^</span></code> operator yields the bitwise XOR (exclusive OR) of its arguments, which
|
||
must be integers or one of them must be a custom object overriding <a class="reference internal" href="datamodel.html#object.__xor__" title="object.__xor__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__xor__()</span></code></a> or
|
||
<a class="reference internal" href="datamodel.html#object.__rxor__" title="object.__rxor__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rxor__()</span></code></a> special methods.</p>
|
||
<p id="index-79">The <code class="docutils literal notranslate"><span class="pre">|</span></code> operator yields the bitwise (inclusive) OR of its arguments, which
|
||
must be integers or one of them must be a custom object overriding <a class="reference internal" href="datamodel.html#object.__or__" title="object.__or__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__or__()</span></code></a> or
|
||
<a class="reference internal" href="datamodel.html#object.__ror__" title="object.__ror__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ror__()</span></code></a> special methods.</p>
|
||
</section>
|
||
<section id="comparisons">
|
||
<span id="id13"></span><h2><span class="section-number">6.10. </span>Comparisons<a class="headerlink" href="#comparisons" title="Link to this heading">¶</a></h2>
|
||
<p id="index-80">Unlike C, all comparison operations in Python have the same priority, which is
|
||
lower than that of any arithmetic, shifting or bitwise operation. Also unlike
|
||
C, expressions like <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre"><</span> <span class="pre">b</span> <span class="pre"><</span> <span class="pre">c</span></code> have the interpretation that is conventional
|
||
in mathematics:</p>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-comparison">comparison</strong>: <a class="reference internal" href="#grammar-token-python-grammar-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a> (<a class="reference internal" href="#grammar-token-python-grammar-comp_operator"><code class="xref docutils literal notranslate"><span class="pre">comp_operator</span></code></a> <a class="reference internal" href="#grammar-token-python-grammar-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a>)*
|
||
<strong id="grammar-token-python-grammar-comp_operator">comp_operator</strong>: <span class="sx">"<"</span> | <span class="sx">">"</span> | <span class="sx">"=="</span> | <span class="sx">">="</span> | <span class="sx">"<="</span> | <span class="sx">"!="</span>
|
||
| <span class="sx">"is"</span> [<span class="sx">"not"</span>] | [<span class="sx">"not"</span>] <span class="sx">"in"</span>
|
||
</pre>
|
||
<p>Comparisons yield boolean values: <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>. Custom
|
||
<em class="dfn">rich comparison methods</em> may return non-boolean values. In this case
|
||
Python will call <a class="reference internal" href="../builtins/functions.html#bool" title="bool"><code class="xref py py-func docutils literal notranslate"><span class="pre">bool()</span></code></a> on such value in boolean contexts.</p>
|
||
<p id="index-81">Comparisons can be chained arbitrarily, e.g., <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span> <span class="pre"><=</span> <span class="pre">z</span></code> is equivalent to
|
||
<code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span> <span class="pre">and</span> <span class="pre">y</span> <span class="pre"><=</span> <span class="pre">z</span></code>, except that <code class="docutils literal notranslate"><span class="pre">y</span></code> is evaluated only once (but in both
|
||
cases <code class="docutils literal notranslate"><span class="pre">z</span></code> is not evaluated at all when <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span></code> is found to be false).</p>
|
||
<p>Formally, if <em>a</em>, <em>b</em>, <em>c</em>, …, <em>y</em>, <em>z</em> are expressions and <em>op1</em>, <em>op2</em>, …,
|
||
<em>opN</em> are comparison operators, then <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">op1</span> <span class="pre">b</span> <span class="pre">op2</span> <span class="pre">c</span> <span class="pre">...</span> <span class="pre">y</span> <span class="pre">opN</span> <span class="pre">z</span></code> is equivalent
|
||
to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">op1</span> <span class="pre">b</span> <span class="pre">and</span> <span class="pre">b</span> <span class="pre">op2</span> <span class="pre">c</span> <span class="pre">and</span> <span class="pre">...</span> <span class="pre">y</span> <span class="pre">opN</span> <span class="pre">z</span></code>, except that each expression is
|
||
evaluated at most once.</p>
|
||
<p>Note that <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">op1</span> <span class="pre">b</span> <span class="pre">op2</span> <span class="pre">c</span></code> doesn’t imply any kind of comparison between <em>a</em> and
|
||
<em>c</em>, so that, e.g., <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span> <span class="pre">></span> <span class="pre">z</span></code> is perfectly legal (though perhaps not
|
||
pretty).</p>
|
||
<section id="value-comparisons">
|
||
<span id="expressions-value-comparisons"></span><h3><span class="section-number">6.10.1. </span>Value comparisons<a class="headerlink" href="#value-comparisons" title="Link to this heading">¶</a></h3>
|
||
<p>The operators <code class="docutils literal notranslate"><span class="pre"><</span></code>, <code class="docutils literal notranslate"><span class="pre">></span></code>, <code class="docutils literal notranslate"><span class="pre">==</span></code>, <code class="docutils literal notranslate"><span class="pre">>=</span></code>, <code class="docutils literal notranslate"><span class="pre"><=</span></code>, and <code class="docutils literal notranslate"><span class="pre">!=</span></code> compare the
|
||
values of two objects. The objects do not need to have the same type.</p>
|
||
<p>Chapter <a class="reference internal" href="datamodel.html#objects"><span class="std std-ref">Objects, values and types</span></a> states that objects have a value (in addition to type
|
||
and identity). The value of an object is a rather abstract notion in Python:
|
||
For example, there is no canonical access method for an object’s value. Also,
|
||
there is no requirement that the value of an object should be constructed in a
|
||
particular way, e.g. comprised of all its data attributes. Comparison operators
|
||
implement a particular notion of what the value of an object is. One can think
|
||
of them as defining the value of an object indirectly, by means of their
|
||
comparison implementation.</p>
|
||
<p>Because all types are (direct or indirect) subtypes of <a class="reference internal" href="../builtins/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>, they
|
||
inherit the default comparison behavior from <code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code>. Types can
|
||
customize their comparison behavior by implementing
|
||
<em class="dfn">rich comparison methods</em> like <a class="reference internal" href="datamodel.html#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a>, described in
|
||
<a class="reference internal" href="datamodel.html#customization"><span class="std std-ref">Basic customization</span></a>.</p>
|
||
<p>The default behavior for equality comparison (<code class="docutils literal notranslate"><span class="pre">==</span></code> and <code class="docutils literal notranslate"><span class="pre">!=</span></code>) is based on
|
||
the identity of the objects. Hence, equality comparison of instances with the
|
||
same identity results in equality, and equality comparison of instances with
|
||
different identities results in inequality. A motivation for this default
|
||
behavior is the desire that all objects should be reflexive (i.e. <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">y</span></code>
|
||
implies <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code>).</p>
|
||
<p>A default order comparison (<code class="docutils literal notranslate"><span class="pre"><</span></code>, <code class="docutils literal notranslate"><span class="pre">></span></code>, <code class="docutils literal notranslate"><span class="pre"><=</span></code>, and <code class="docutils literal notranslate"><span class="pre">>=</span></code>) is not provided;
|
||
an attempt raises <a class="reference internal" href="../builtins/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>. A motivation for this default behavior is
|
||
the lack of a similar invariant as for equality.</p>
|
||
<p>The behavior of the default equality comparison, that instances with different
|
||
identities are always unequal, may be in contrast to what types will need that
|
||
have a sensible definition of object value and value-based equality. Such
|
||
types will need to customize their comparison behavior, and in fact, a number
|
||
of built-in types have done that.</p>
|
||
<p>The following list describes the comparison behavior of the most important
|
||
built-in types.</p>
|
||
<ul>
|
||
<li><p>Numbers of built-in numeric types (<a class="reference internal" href="../builtins/stdtypes.html#typesnumeric"><span class="std std-ref">Numeric Types — int, float, complex</span></a>) and of the standard
|
||
library types <a class="reference internal" href="../library/fractions.html#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">fractions.Fraction</span></code></a> and <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">decimal.Decimal</span></code></a> can be
|
||
compared within and across their types, with the restriction that complex
|
||
numbers do not support order comparison. Within the limits of the types
|
||
involved, they compare mathematically (algorithmically) correct without loss
|
||
of precision.</p>
|
||
<p>The not-a-number values <code class="docutils literal notranslate"><span class="pre">float('NaN')</span></code> and <code class="docutils literal notranslate"><span class="pre">decimal.Decimal('NaN')</span></code> are
|
||
special. Any ordered comparison of a number to a not-a-number value is false.
|
||
A counter-intuitive implication is that not-a-number values are not equal to
|
||
themselves. For example, if <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">float('NaN')</span></code>, <code class="docutils literal notranslate"><span class="pre">3</span> <span class="pre"><</span> <span class="pre">x</span></code>, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">3</span></code> and
|
||
<code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">x</span></code> are all false, while <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">!=</span> <span class="pre">x</span></code> is true. This behavior is
|
||
compliant with IEEE 754.</p>
|
||
</li>
|
||
<li><p><code class="docutils literal notranslate"><span class="pre">None</span></code> and <a class="reference internal" href="../builtins/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> are singletons. <span class="target" id="index-82"></span><a class="pep reference external" href="https://peps.python.org/pep-0008/"><strong>PEP 8</strong></a> advises that
|
||
comparisons for singletons should always be done with <code class="docutils literal notranslate"><span class="pre">is</span></code> or <code class="docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code>,
|
||
never the equality operators.</p></li>
|
||
<li><p>Binary sequences (instances of <a class="reference internal" href="../builtins/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> or <a class="reference internal" href="../builtins/stdtypes.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>) can be
|
||
compared within and across their types. They compare lexicographically using
|
||
the numeric values of their elements.</p></li>
|
||
<li><p>Strings (instances of <a class="reference internal" href="../builtins/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>) compare lexicographically using the
|
||
numerical Unicode code points (the result of the built-in function
|
||
<a class="reference internal" href="../builtins/functions.html#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a>) of their characters. <a class="footnote-reference brackets" href="#id24" id="id14" role="doc-noteref"><span class="fn-bracket">[</span>3<span class="fn-bracket">]</span></a></p>
|
||
<p>Strings and binary sequences cannot be directly compared.</p>
|
||
</li>
|
||
<li><p>Sequences (instances of <a class="reference internal" href="../builtins/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>, <a class="reference internal" href="../builtins/stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a>, or <a class="reference internal" href="../builtins/stdtypes.html#range" title="range"><code class="xref py py-class docutils literal notranslate"><span class="pre">range</span></code></a>) can
|
||
be compared only within each of their types, with the restriction that ranges
|
||
do not support order comparison. Equality comparison across these types
|
||
results in inequality, and ordering comparison across these types raises
|
||
<a class="reference internal" href="../builtins/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
|
||
<p>Sequences compare lexicographically using comparison of corresponding
|
||
elements. The built-in containers typically assume identical objects are
|
||
equal to themselves. That lets them bypass equality tests for identical
|
||
objects to improve performance and to maintain their internal invariants.</p>
|
||
<p>Lexicographical comparison between built-in collections works as follows:</p>
|
||
<ul class="simple">
|
||
<li><p>For two collections to compare equal, they must be of the same type, have
|
||
the same length, and each pair of corresponding elements must compare
|
||
equal (for example, <code class="docutils literal notranslate"><span class="pre">[1,2]</span> <span class="pre">==</span> <span class="pre">(1,2)</span></code> is false because the type is not the
|
||
same).</p></li>
|
||
<li><p>Collections that support order comparison are ordered the same as their
|
||
first unequal elements (for example, <code class="docutils literal notranslate"><span class="pre">[1,2,x]</span> <span class="pre"><=</span> <span class="pre">[1,2,y]</span></code> has the same
|
||
value as <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><=</span> <span class="pre">y</span></code>). If a corresponding element does not exist, the
|
||
shorter collection is ordered first (for example, <code class="docutils literal notranslate"><span class="pre">[1,2]</span> <span class="pre"><</span> <span class="pre">[1,2,3]</span></code> is
|
||
true).</p></li>
|
||
</ul>
|
||
</li>
|
||
<li><p>Mappings (instances of <a class="reference internal" href="../builtins/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>) compare equal if and only if they have
|
||
equal <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> pairs. Equality comparison of the keys and values
|
||
enforces reflexivity.</p>
|
||
<p>Order comparisons (<code class="docutils literal notranslate"><span class="pre"><</span></code>, <code class="docutils literal notranslate"><span class="pre">></span></code>, <code class="docutils literal notranslate"><span class="pre"><=</span></code>, and <code class="docutils literal notranslate"><span class="pre">>=</span></code>) raise <a class="reference internal" href="../builtins/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
|
||
</li>
|
||
<li><p>Sets (instances of <a class="reference internal" href="../builtins/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> or <a class="reference internal" href="../builtins/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>) can be compared within
|
||
and across their types.</p>
|
||
<p>They define order
|
||
comparison operators to mean subset and superset tests. Those relations do
|
||
not define total orderings (for example, the two sets <code class="docutils literal notranslate"><span class="pre">{1,2}</span></code> and <code class="docutils literal notranslate"><span class="pre">{2,3}</span></code>
|
||
are not equal, nor subsets of one another, nor supersets of one
|
||
another). Accordingly, sets are not appropriate arguments for functions
|
||
which depend on total ordering (for example, <a class="reference internal" href="../builtins/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a>, <a class="reference internal" href="../builtins/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a>, and
|
||
<a class="reference internal" href="../builtins/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> produce undefined results given a list of sets as inputs).</p>
|
||
<p>Comparison of sets enforces reflexivity of its elements.</p>
|
||
</li>
|
||
<li><p>Most other built-in types have no comparison methods implemented, so they
|
||
inherit the default comparison behavior.</p></li>
|
||
</ul>
|
||
<p>User-defined classes that customize their comparison behavior should follow
|
||
some consistency rules, if possible:</p>
|
||
<ul>
|
||
<li><p>Equality comparison should be reflexive.
|
||
In other words, identical objects should compare equal:</p>
|
||
<blockquote>
|
||
<div><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">y</span></code> implies <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code></p>
|
||
</div></blockquote>
|
||
</li>
|
||
<li><p>Comparison should be symmetric.
|
||
In other words, the following expressions should have the same result:</p>
|
||
<blockquote>
|
||
<div><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">==</span> <span class="pre">x</span></code></p>
|
||
<p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">!=</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">!=</span> <span class="pre">x</span></code></p>
|
||
<p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">></span> <span class="pre">x</span></code></p>
|
||
<p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><=</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">>=</span> <span class="pre">x</span></code></p>
|
||
</div></blockquote>
|
||
</li>
|
||
<li><p>Comparison should be transitive.
|
||
The following (non-exhaustive) examples illustrate that:</p>
|
||
<blockquote>
|
||
<div><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">></span> <span class="pre">y</span> <span class="pre">and</span> <span class="pre">y</span> <span class="pre">></span> <span class="pre">z</span></code> implies <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">></span> <span class="pre">z</span></code></p>
|
||
<p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span> <span class="pre">and</span> <span class="pre">y</span> <span class="pre"><=</span> <span class="pre">z</span></code> implies <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">z</span></code></p>
|
||
</div></blockquote>
|
||
</li>
|
||
<li><p>Inverse comparison should result in the boolean negation.
|
||
In other words, the following expressions should have the same result:</p>
|
||
<blockquote>
|
||
<div><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">x</span> <span class="pre">!=</span> <span class="pre">y</span></code></p>
|
||
<p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">x</span> <span class="pre">>=</span> <span class="pre">y</span></code> (for total ordering)</p>
|
||
<p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">></span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">x</span> <span class="pre"><=</span> <span class="pre">y</span></code> (for total ordering)</p>
|
||
</div></blockquote>
|
||
<p>The last two expressions apply to totally ordered collections (e.g. to
|
||
sequences, but not to sets or mappings). See also the
|
||
<a class="reference internal" href="../library/functools.html#functools.total_ordering" title="functools.total_ordering"><code class="xref py py-deco docutils literal notranslate"><span class="pre">@~functools.total_ordering</span></code></a> decorator.</p>
|
||
</li>
|
||
<li><p>The <a class="reference internal" href="../builtins/functions.html#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a> result should be consistent with equality.
|
||
Objects that are equal should either have the same hash value,
|
||
or be marked as unhashable.</p></li>
|
||
</ul>
|
||
<p>Python does not enforce these consistency rules. In fact, the not-a-number
|
||
values are an example for not following these rules.</p>
|
||
</section>
|
||
<section id="membership-test-operations">
|
||
<span id="membership-test-details"></span><span id="not-in"></span><span id="in"></span><h3><span class="section-number">6.10.2. </span>Membership test operations<a class="headerlink" href="#membership-test-operations" title="Link to this heading">¶</a></h3>
|
||
<p>The operators <a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> and <a class="reference internal" href="#not-in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code></a> test for membership. <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span>
|
||
<span class="pre">s</span></code> evaluates to <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>x</em> is a member of <em>s</em>, and <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.
|
||
<code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">not</span> <span class="pre">in</span> <span class="pre">s</span></code> returns the negation of <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">s</span></code>. All built-in sequences and
|
||
set types support this as well as dictionary, for which <code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code> tests
|
||
whether the dictionary has a given key. For container types such as list, tuple,
|
||
set, frozenset, dict, or collections.deque, the expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> is equivalent
|
||
to <code class="docutils literal notranslate"><span class="pre">any(x</span> <span class="pre">is</span> <span class="pre">e</span> <span class="pre">or</span> <span class="pre">x</span> <span class="pre">==</span> <span class="pre">e</span> <span class="pre">for</span> <span class="pre">e</span> <span class="pre">in</span> <span class="pre">y)</span></code>.</p>
|
||
<p>For the string and bytes types, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code> if and only if <em>x</em> is a
|
||
substring of <em>y</em>. An equivalent test is <code class="docutils literal notranslate"><span class="pre">y.find(x)</span> <span class="pre">!=</span> <span class="pre">-1</span></code>. Empty strings are
|
||
always considered to be a substring of any other string, so <code class="docutils literal notranslate"><span class="pre">""</span> <span class="pre">in</span> <span class="pre">"abc"</span></code> will
|
||
return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
|
||
<p>For user-defined classes which define the <a class="reference internal" href="datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> method, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span>
|
||
<span class="pre">y</span></code> returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if <code class="docutils literal notranslate"><span class="pre">y.__contains__(x)</span></code> returns a true value, and
|
||
<code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
|
||
<p>For user-defined classes which do not define <a class="reference internal" href="datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> but do define
|
||
<a class="reference internal" href="datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code> if some value <code class="docutils literal notranslate"><span class="pre">z</span></code>, for which the
|
||
expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">z</span> <span class="pre">or</span> <span class="pre">x</span> <span class="pre">==</span> <span class="pre">z</span></code> is true, is produced while iterating over <code class="docutils literal notranslate"><span class="pre">y</span></code>.
|
||
If an exception is raised during the iteration, it is as if <a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> raised
|
||
that exception.</p>
|
||
<p>Lastly, the old-style iteration protocol is tried: if a class defines
|
||
<a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code> if and only if there is a non-negative
|
||
integer index <em>i</em> such that <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">y[i]</span> <span class="pre">or</span> <span class="pre">x</span> <span class="pre">==</span> <span class="pre">y[i]</span></code>, and no lower integer index
|
||
raises the <a class="reference internal" href="../builtins/exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> exception. (If any other exception is raised, it is as
|
||
if <a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> raised that exception).</p>
|
||
<p id="index-83">The operator <a class="reference internal" href="#not-in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code></a> is defined to have the inverse truth value of
|
||
<a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a>.</p>
|
||
</section>
|
||
<section id="is-not">
|
||
<span id="is"></span><span id="index-84"></span><span id="identity-comparisons"></span><h3><span class="section-number">6.10.3. </span>Identity comparisons<a class="headerlink" href="#is-not" title="Link to this heading">¶</a></h3>
|
||
<p>The operators <a class="reference internal" href="#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a> and <a class="reference internal" href="#is-not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code></a> test for an object’s identity: <code class="docutils literal notranslate"><span class="pre">x</span>
|
||
<span class="pre">is</span> <span class="pre">y</span></code> is true if and only if <em>x</em> and <em>y</em> are the same object. An Object’s identity
|
||
is determined using the <a class="reference internal" href="../builtins/functions.html#id" title="id"><code class="xref py py-meth docutils literal notranslate"><span class="pre">id()</span></code></a> function. <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">not</span> <span class="pre">y</span></code> yields the inverse
|
||
truth value. <a class="footnote-reference brackets" href="#id25" id="id15" role="doc-noteref"><span class="fn-bracket">[</span>4<span class="fn-bracket">]</span></a></p>
|
||
</section>
|
||
</section>
|
||
<section id="boolean-operations">
|
||
<span id="not"></span><span id="or"></span><span id="and"></span><span id="booleans"></span><h2><span class="section-number">6.11. </span>Boolean operations<a class="headerlink" href="#boolean-operations" title="Link to this heading">¶</a></h2>
|
||
<pre class="highlight" id="index-85">
|
||
<strong id="grammar-token-python-grammar-or_test">or_test</strong>: <a class="reference internal" href="#grammar-token-python-grammar-and_test"><code class="xref docutils literal notranslate"><span class="pre">and_test</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> <span class="sx">"or"</span> <a class="reference internal" href="#grammar-token-python-grammar-and_test"><code class="xref docutils literal notranslate"><span class="pre">and_test</span></code></a>
|
||
<strong id="grammar-token-python-grammar-and_test">and_test</strong>: <a class="reference internal" href="#grammar-token-python-grammar-not_test"><code class="xref docutils literal notranslate"><span class="pre">not_test</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-and_test"><code class="xref docutils literal notranslate"><span class="pre">and_test</span></code></a> <span class="sx">"and"</span> <a class="reference internal" href="#grammar-token-python-grammar-not_test"><code class="xref docutils literal notranslate"><span class="pre">not_test</span></code></a>
|
||
<strong id="grammar-token-python-grammar-not_test">not_test</strong>: <a class="reference internal" href="#grammar-token-python-grammar-comparison"><code class="xref docutils literal notranslate"><span class="pre">comparison</span></code></a> | <span class="sx">"not"</span> <a class="reference internal" href="#grammar-token-python-grammar-not_test"><code class="xref docutils literal notranslate"><span class="pre">not_test</span></code></a>
|
||
</pre>
|
||
<p>In the context of Boolean operations, and also when expressions are used by
|
||
control flow statements, the following values are interpreted as false:
|
||
<code class="docutils literal notranslate"><span class="pre">False</span></code>, <code class="docutils literal notranslate"><span class="pre">None</span></code>, numeric zero of all types, and empty strings and containers
|
||
(including strings, tuples, lists, dictionaries, sets and frozensets). All
|
||
other values are interpreted as true. User-defined objects can customize their
|
||
truth value by providing a <a class="reference internal" href="datamodel.html#object.__bool__" title="object.__bool__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__bool__()</span></code></a> method.</p>
|
||
<p id="index-86">The operator <a class="reference internal" href="#not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span></code></a> yields <code class="docutils literal notranslate"><span class="pre">True</span></code> if its argument is false, <code class="docutils literal notranslate"><span class="pre">False</span></code>
|
||
otherwise.</p>
|
||
<p id="index-87">The expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">and</span> <span class="pre">y</span></code> first evaluates <em>x</em>; if <em>x</em> is false, its value is
|
||
returned; otherwise, <em>y</em> is evaluated and the resulting value is returned.</p>
|
||
<p id="index-88">The expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">or</span> <span class="pre">y</span></code> first evaluates <em>x</em>; if <em>x</em> is true, its value is
|
||
returned; otherwise, <em>y</em> is evaluated and the resulting value is returned.</p>
|
||
<p>Note that neither <a class="reference internal" href="#and"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">and</span></code></a> nor <a class="reference internal" href="#or"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">or</span></code></a> restrict the value and type
|
||
they return to <code class="docutils literal notranslate"><span class="pre">False</span></code> and <code class="docutils literal notranslate"><span class="pre">True</span></code>, but rather return the last evaluated
|
||
argument. This is sometimes useful, e.g., if <code class="docutils literal notranslate"><span class="pre">s</span></code> is a string that should be
|
||
replaced by a default value if it is empty, the expression <code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">or</span> <span class="pre">'foo'</span></code> yields
|
||
the desired value. Because <a class="reference internal" href="#not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span></code></a> has to create a new value, it
|
||
returns a boolean value regardless of the type of its argument
|
||
(for example, <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">'foo'</span></code> produces <code class="docutils literal notranslate"><span class="pre">False</span></code> rather than <code class="docutils literal notranslate"><span class="pre">''</span></code>.)</p>
|
||
</section>
|
||
<section id="assignment-expressions">
|
||
<span id="index-89"></span><span id="id16"></span><h2><span class="section-number">6.12. </span>Assignment expressions<a class="headerlink" href="#assignment-expressions" title="Link to this heading">¶</a></h2>
|
||
<pre class="highlight">
|
||
<strong id="grammar-token-python-grammar-assignment_expression">assignment_expression</strong>: [<a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> <span class="sx">":="</span>] <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
|
||
</pre>
|
||
<p>An assignment expression (sometimes also called a “named expression” or
|
||
“walrus”) assigns an <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression</span></code></a> to an
|
||
<a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref std std-token docutils literal notranslate"><span class="pre">identifier</span></code></a>, while also returning the value of the
|
||
<code class="xref std std-token docutils literal notranslate"><span class="pre">expression</span></code>.</p>
|
||
<p>One common use case is when handling matched regular expressions:</p>
|
||
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">matching</span> <span class="o">:=</span> <span class="n">pattern</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="n">data</span><span class="p">):</span>
|
||
<span class="n">do_something</span><span class="p">(</span><span class="n">matching</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Or, when processing a file stream in chunks:</p>
|
||
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">while</span> <span class="n">chunk</span> <span class="o">:=</span> <span class="n">file</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">9000</span><span class="p">):</span>
|
||
<span class="n">process</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Assignment expressions must be surrounded by parentheses when
|
||
used as expression statements and when used as sub-expressions in
|
||
slicing, conditional, lambda,
|
||
keyword-argument, and comprehension-if expressions and
|
||
in <code class="docutils literal notranslate"><span class="pre">assert</span></code>, <code class="docutils literal notranslate"><span class="pre">with</span></code>, and <code class="docutils literal notranslate"><span class="pre">assignment</span></code> statements.
|
||
In all other places where they can be used, parentheses are not required,
|
||
including in <code class="docutils literal notranslate"><span class="pre">if</span></code> and <code class="docutils literal notranslate"><span class="pre">while</span></code> statements.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">Added in version 3.8: </span>See <span class="target" id="index-90"></span><a class="pep reference external" href="https://peps.python.org/pep-0572/"><strong>PEP 572</strong></a> for more details about assignment expressions.</p>
|
||
</div>
|
||
</section>
|
||
<section id="conditional-expressions">
|
||
<span id="if-expr"></span><h2><span class="section-number">6.13. </span>Conditional expressions<a class="headerlink" href="#conditional-expressions" title="Link to this heading">¶</a></h2>
|
||
<pre class="highlight" id="index-91">
|
||
<strong id="grammar-token-python-grammar-conditional_expression">conditional_expression</strong>: <a class="reference internal" href="#grammar-token-python-grammar-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> [<span class="sx">"if"</span> <a class="reference internal" href="#grammar-token-python-grammar-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> <span class="sx">"else"</span> <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
|
||
<strong id="grammar-token-python-grammar-expression">expression</strong>: <a class="reference internal" href="#grammar-token-python-grammar-conditional_expression"><code class="xref docutils literal notranslate"><span class="pre">conditional_expression</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-lambda_expr"><code class="xref docutils literal notranslate"><span class="pre">lambda_expr</span></code></a>
|
||
</pre>
|
||
<p>A conditional expression (sometimes called a “ternary operator”) is an
|
||
alternative to the if-else statement. As it is an expression, it returns a value
|
||
and can appear as a sub-expression.</p>
|
||
<p>The expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">if</span> <span class="pre">C</span> <span class="pre">else</span> <span class="pre">y</span></code> first evaluates the condition, <em>C</em> rather than <em>x</em>.
|
||
If <em>C</em> is true, <em>x</em> is evaluated and its value is returned; otherwise, <em>y</em> is
|
||
evaluated and its value is returned.</p>
|
||
<p>See <span class="target" id="index-92"></span><a class="pep reference external" href="https://peps.python.org/pep-0308/"><strong>PEP 308</strong></a> for more details about conditional expressions.</p>
|
||
</section>
|
||
<section id="lambda">
|
||
<span id="lambdas"></span><span id="id17"></span><h2><span class="section-number">6.14. </span>Lambdas<a class="headerlink" href="#lambda" title="Link to this heading">¶</a></h2>
|
||
<pre class="highlight" id="index-93">
|
||
<strong id="grammar-token-python-grammar-lambda_expr">lambda_expr</strong>: <span class="sx">"lambda"</span> [<a class="reference internal" href="compound_stmts.html#grammar-token-python-grammar-parameter_list"><code class="xref docutils literal notranslate"><span class="pre">parameter_list</span></code></a>] <span class="sx">":"</span> <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
|
||
</pre>
|
||
<p>Lambda expressions (sometimes called lambda forms) are used to create anonymous
|
||
functions. The expression <code class="docutils literal notranslate"><span class="pre">lambda</span> <span class="pre">parameters:</span> <span class="pre">expression</span></code> yields a function
|
||
object. The unnamed object behaves like a function object defined with:</p>
|
||
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>def <lambda>(parameters):
|
||
return expression
|
||
</pre></div>
|
||
</div>
|
||
<p>See section <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a> for the syntax of parameter lists. Note that
|
||
functions created with lambda expressions cannot contain statements or
|
||
annotations.</p>
|
||
</section>
|
||
<section id="expression-lists">
|
||
<span id="exprlists"></span><span id="index-94"></span><h2><span class="section-number">6.15. </span>Expression lists<a class="headerlink" href="#expression-lists" title="Link to this heading">¶</a></h2>
|
||
<pre class="highlight" id="index-95">
|
||
<strong id="grammar-token-python-grammar-starred_expression">starred_expression</strong>: <span class="sx">"*"</span> <a class="reference internal" href="#grammar-token-python-grammar-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
|
||
<strong id="grammar-token-python-grammar-flexible_expression">flexible_expression</strong>: <a class="reference internal" href="#grammar-token-python-grammar-assignment_expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-starred_expression"><code class="xref docutils literal notranslate"><span class="pre">starred_expression</span></code></a>
|
||
<strong id="grammar-token-python-grammar-flexible_expression_list">flexible_expression_list</strong>: <a class="reference internal" href="#grammar-token-python-grammar-flexible_expression"><code class="xref docutils literal notranslate"><span class="pre">flexible_expression</span></code></a> (<span class="sx">","</span> <a class="reference internal" href="#grammar-token-python-grammar-flexible_expression"><code class="xref docutils literal notranslate"><span class="pre">flexible_expression</span></code></a>)* [<span class="sx">","</span>]
|
||
<strong id="grammar-token-python-grammar-starred_expression_list">starred_expression_list</strong>: <a class="reference internal" href="#grammar-token-python-grammar-starred_expression"><code class="xref docutils literal notranslate"><span class="pre">starred_expression</span></code></a> (<span class="sx">","</span> <a class="reference internal" href="#grammar-token-python-grammar-starred_expression"><code class="xref docutils literal notranslate"><span class="pre">starred_expression</span></code></a>)* [<span class="sx">","</span>]
|
||
<strong id="grammar-token-python-grammar-expression_list">expression_list</strong>: <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> (<span class="sx">","</span> <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>)* [<span class="sx">","</span>]
|
||
<strong id="grammar-token-python-grammar-yield_list">yield_list</strong>: <a class="reference internal" href="#grammar-token-python-grammar-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-starred_expression"><code class="xref docutils literal notranslate"><span class="pre">starred_expression</span></code></a> <span class="sx">","</span> [<a class="reference internal" href="#grammar-token-python-grammar-starred_expression_list"><code class="xref docutils literal notranslate"><span class="pre">starred_expression_list</span></code></a>]
|
||
</pre>
|
||
<p id="index-96">Except when part of a list or set display, an expression list
|
||
containing at least one comma yields a tuple. The length of
|
||
the tuple is the number of expressions in the list. The expressions are
|
||
evaluated from left to right.</p>
|
||
<p id="index-97">A trailing comma is required only to create a one-item tuple,
|
||
such as <code class="docutils literal notranslate"><span class="pre">1,</span></code>; it is optional in all other cases.
|
||
A single expression without a
|
||
trailing comma doesn’t create a tuple, but rather yields the value of that
|
||
expression. (To create an empty tuple, use an empty pair of parentheses:
|
||
<code class="docutils literal notranslate"><span class="pre">()</span></code>.)</p>
|
||
<section id="index-98">
|
||
<span id="iterable-unpacking"></span><span id="id18"></span><h3><span class="section-number">6.15.1. </span>Iterable unpacking<a class="headerlink" href="#index-98" title="Link to this heading">¶</a></h3>
|
||
<p>In an expression list or tuple, list or set display, any expression
|
||
may be prefixed with an asterisk (<code class="docutils literal notranslate"><span class="pre">*</span></code>).
|
||
This denotes <em class="dfn">iterable unpacking</em>.</p>
|
||
<p>At runtime, the asterisk-prefixed expression must evaluate
|
||
to an <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a>.
|
||
The iterable is expanded into a sequence of items,
|
||
which are included in the new tuple, list, or set, at the site of
|
||
the unpacking.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">Added in version 3.5: </span>Iterable unpacking in expression lists, originally proposed by <span class="target" id="index-99"></span><a class="pep reference external" href="https://peps.python.org/pep-0448/"><strong>PEP 448</strong></a>.</p>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">Added in version 3.11: </span>Any item in an expression list may be starred. See <span class="target" id="index-100"></span><a class="pep reference external" href="https://peps.python.org/pep-0646/"><strong>PEP 646</strong></a>.</p>
|
||
</div>
|
||
</section>
|
||
</section>
|
||
<section id="evaluation-order">
|
||
<span id="evalorder"></span><h2><span class="section-number">6.16. </span>Evaluation order<a class="headerlink" href="#evaluation-order" title="Link to this heading">¶</a></h2>
|
||
<p id="index-101">Python evaluates expressions from left to right. Notice that while evaluating
|
||
an assignment, the right-hand side is evaluated before the left-hand side.</p>
|
||
<p>In the following lines, expressions will be evaluated in the arithmetic order of
|
||
their suffixes:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">expr1</span><span class="p">,</span> <span class="n">expr2</span><span class="p">,</span> <span class="n">expr3</span><span class="p">,</span> <span class="n">expr4</span>
|
||
<span class="p">(</span><span class="n">expr1</span><span class="p">,</span> <span class="n">expr2</span><span class="p">,</span> <span class="n">expr3</span><span class="p">,</span> <span class="n">expr4</span><span class="p">)</span>
|
||
<span class="p">{</span><span class="n">expr1</span><span class="p">:</span> <span class="n">expr2</span><span class="p">,</span> <span class="n">expr3</span><span class="p">:</span> <span class="n">expr4</span><span class="p">}</span>
|
||
<span class="n">expr1</span> <span class="o">+</span> <span class="n">expr2</span> <span class="o">*</span> <span class="p">(</span><span class="n">expr3</span> <span class="o">-</span> <span class="n">expr4</span><span class="p">)</span>
|
||
<span class="n">expr1</span><span class="p">(</span><span class="n">expr2</span><span class="p">,</span> <span class="n">expr3</span><span class="p">,</span> <span class="o">*</span><span class="n">expr4</span><span class="p">,</span> <span class="o">**</span><span class="n">expr5</span><span class="p">)</span>
|
||
<span class="n">expr3</span><span class="p">,</span> <span class="n">expr4</span> <span class="o">=</span> <span class="n">expr1</span><span class="p">,</span> <span class="n">expr2</span>
|
||
</pre></div>
|
||
</div>
|
||
</section>
|
||
<section id="operator-precedence">
|
||
<span id="operator-summary"></span><span id="id19"></span><h2><span class="section-number">6.17. </span>Operator precedence<a class="headerlink" href="#operator-precedence" title="Link to this heading">¶</a></h2>
|
||
<p id="index-102">The following table summarizes the operator precedence in Python, from highest
|
||
precedence (most binding) to lowest precedence (least binding). Operators in
|
||
the same box have the same precedence. Unless the syntax is explicitly given,
|
||
operators are binary. Operators in the same box group left to right (except for
|
||
exponentiation and conditional expressions, which group from right to left).</p>
|
||
<p>Note that comparisons, membership tests, and identity tests, all have the same
|
||
precedence and have a left-to-right chaining feature as described in the
|
||
<a class="reference internal" href="#comparisons"><span class="std std-ref">Comparisons</span></a> section.</p>
|
||
<table class="docutils align-default">
|
||
<thead>
|
||
<tr class="row-odd"><th class="head"><p>Operator</p></th>
|
||
<th class="head"><p>Description</p></th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">(expressions...)</span></code>,</p>
|
||
<p><code class="docutils literal notranslate"><span class="pre">[expressions...]</span></code>,
|
||
<code class="docutils literal notranslate"><span class="pre">{key:</span> <span class="pre">value...}</span></code>,
|
||
<code class="docutils literal notranslate"><span class="pre">{expressions...}</span></code></p>
|
||
</td>
|
||
<td><p>Binding or parenthesized
|
||
expression,
|
||
list display,
|
||
dictionary display,
|
||
set display</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">x[index]</span></code>, <code class="docutils literal notranslate"><span class="pre">x[index:index]</span></code>
|
||
<code class="docutils literal notranslate"><span class="pre">x(arguments...)</span></code>, <code class="docutils literal notranslate"><span class="pre">x.attribute</span></code></p></td>
|
||
<td><p>Subscription (including slicing),
|
||
call, attribute reference</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><a class="reference internal" href="#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span> <span class="pre">x</span></code></a></p></td>
|
||
<td><p>Await expression</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">**</span></code></p></td>
|
||
<td><p>Exponentiation <a class="footnote-reference brackets" href="#id26" id="id20" role="doc-noteref"><span class="fn-bracket">[</span>5<span class="fn-bracket">]</span></a></p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">+x</span></code>, <code class="docutils literal notranslate"><span class="pre">-x</span></code>, <code class="docutils literal notranslate"><span class="pre">~x</span></code></p></td>
|
||
<td><p>Positive, negative, bitwise NOT</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">@</span></code>, <code class="docutils literal notranslate"><span class="pre">/</span></code>, <code class="docutils literal notranslate"><span class="pre">//</span></code>, <code class="docutils literal notranslate"><span class="pre">%</span></code></p></td>
|
||
<td><p>Multiplication, matrix
|
||
multiplication, division, floor
|
||
division, remainder <a class="footnote-reference brackets" href="#id27" id="id21" role="doc-noteref"><span class="fn-bracket">[</span>6<span class="fn-bracket">]</span></a></p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">+</span></code>, <code class="docutils literal notranslate"><span class="pre">-</span></code></p></td>
|
||
<td><p>Addition and subtraction</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre"><<</span></code>, <code class="docutils literal notranslate"><span class="pre">>></span></code></p></td>
|
||
<td><p>Shifts</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">&</span></code></p></td>
|
||
<td><p>Bitwise AND</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">^</span></code></p></td>
|
||
<td><p>Bitwise XOR</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">|</span></code></p></td>
|
||
<td><p>Bitwise OR</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a>, <a class="reference internal" href="#not-in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code></a>,
|
||
<a class="reference internal" href="#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a>, <a class="reference internal" href="#is-not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code></a>, <code class="docutils literal notranslate"><span class="pre"><</span></code>,
|
||
<code class="docutils literal notranslate"><span class="pre"><=</span></code>, <code class="docutils literal notranslate"><span class="pre">></span></code>, <code class="docutils literal notranslate"><span class="pre">>=</span></code>, <code class="docutils literal notranslate"><span class="pre">!=</span></code>, <code class="docutils literal notranslate"><span class="pre">==</span></code></p></td>
|
||
<td><p>Comparisons, including membership
|
||
tests and identity tests</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><a class="reference internal" href="#not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">x</span></code></a></p></td>
|
||
<td><p>Boolean NOT</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><a class="reference internal" href="#and"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">and</span></code></a></p></td>
|
||
<td><p>Boolean AND</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><a class="reference internal" href="#or"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">or</span></code></a></p></td>
|
||
<td><p>Boolean OR</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><a class="reference internal" href="#if-expr"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> – <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></p></td>
|
||
<td><p>Conditional expression</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><a class="reference internal" href="#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a></p></td>
|
||
<td><p>Lambda expression</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">:=</span></code></p></td>
|
||
<td><p>Assignment expression</p></td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
<p class="rubric">Footnotes</p>
|
||
<aside class="footnote-list brackets">
|
||
<aside class="footnote brackets" id="id22" role="doc-footnote">
|
||
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id11">1</a><span class="fn-bracket">]</span></span>
|
||
<p>While <code class="docutils literal notranslate"><span class="pre">abs(x%y)</span> <span class="pre"><</span> <span class="pre">abs(y)</span></code> is true mathematically, for floats it may not be
|
||
true numerically due to roundoff. For example, and assuming a platform on which
|
||
a Python float is an IEEE 754 double-precision number, in order that <code class="docutils literal notranslate"><span class="pre">-1e-100</span> <span class="pre">%</span>
|
||
<span class="pre">1e100</span></code> have the same sign as <code class="docutils literal notranslate"><span class="pre">1e100</span></code>, the computed result is <code class="docutils literal notranslate"><span class="pre">-1e-100</span> <span class="pre">+</span>
|
||
<span class="pre">1e100</span></code>, which is numerically exactly equal to <code class="docutils literal notranslate"><span class="pre">1e100</span></code>. The function
|
||
<a class="reference internal" href="../library/math.html#math.fmod" title="math.fmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.fmod()</span></code></a> returns a result whose sign matches the sign of the
|
||
first argument instead, and so returns <code class="docutils literal notranslate"><span class="pre">-1e-100</span></code> in this case. Which approach
|
||
is more appropriate depends on the application.</p>
|
||
</aside>
|
||
<aside class="footnote brackets" id="id23" role="doc-footnote">
|
||
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id12">2</a><span class="fn-bracket">]</span></span>
|
||
<p>If x is very close to an exact integer multiple of y, it’s possible for
|
||
<code class="docutils literal notranslate"><span class="pre">x//y</span></code> to be one larger than <code class="docutils literal notranslate"><span class="pre">(x-x%y)//y</span></code> due to rounding. In such
|
||
cases, Python returns the latter result, in order to preserve that
|
||
<code class="docutils literal notranslate"><span class="pre">divmod(x,y)[0]</span> <span class="pre">*</span> <span class="pre">y</span> <span class="pre">+</span> <span class="pre">x</span> <span class="pre">%</span> <span class="pre">y</span></code> be very close to <code class="docutils literal notranslate"><span class="pre">x</span></code>.</p>
|
||
</aside>
|
||
<aside class="footnote brackets" id="id24" role="doc-footnote">
|
||
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id14">3</a><span class="fn-bracket">]</span></span>
|
||
<p>The Unicode standard distinguishes between <em class="dfn">code points</em>
|
||
(e.g. U+0041) and <em class="dfn">abstract characters</em> (e.g. “LATIN CAPITAL LETTER A”).
|
||
While most abstract characters in Unicode are only represented using one
|
||
code point, there is a number of abstract characters that can in addition be
|
||
represented using a sequence of more than one code point. For example, the
|
||
abstract character “LATIN CAPITAL LETTER C WITH CEDILLA” can be represented
|
||
as a single <em class="dfn">precomposed character</em> at code position U+00C7, or as a
|
||
sequence of a <em class="dfn">base character</em> at code position U+0043 (LATIN CAPITAL
|
||
LETTER C), followed by a <em class="dfn">combining character</em> at code position U+0327
|
||
(COMBINING CEDILLA).</p>
|
||
<p>The comparison operators on strings compare at the level of Unicode code
|
||
points. This may be counter-intuitive to humans. For example,
|
||
<code class="docutils literal notranslate"><span class="pre">"\u00C7"</span> <span class="pre">==</span> <span class="pre">"\u0043\u0327"</span></code> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, even though both strings
|
||
represent the same abstract character “LATIN CAPITAL LETTER C WITH CEDILLA”.</p>
|
||
<p>To compare strings at the level of abstract characters (that is, in a way
|
||
intuitive to humans), use <a class="reference internal" href="../library/unicodedata.html#unicodedata.normalize" title="unicodedata.normalize"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicodedata.normalize()</span></code></a>.</p>
|
||
</aside>
|
||
<aside class="footnote brackets" id="id25" role="doc-footnote">
|
||
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id15">4</a><span class="fn-bracket">]</span></span>
|
||
<p>Due to automatic garbage-collection, free lists, and the dynamic nature of
|
||
descriptors, you may notice seemingly unusual behaviour in certain uses of
|
||
the <a class="reference internal" href="#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a> operator, like those involving comparisons between instance
|
||
methods, or constants. Check their documentation for more info.</p>
|
||
</aside>
|
||
<aside class="footnote brackets" id="id26" role="doc-footnote">
|
||
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id20">5</a><span class="fn-bracket">]</span></span>
|
||
<p>The power operator <code class="docutils literal notranslate"><span class="pre">**</span></code> binds less tightly than an arithmetic or
|
||
bitwise unary operator on its right, that is, <code class="docutils literal notranslate"><span class="pre">2**-1</span></code> is <code class="docutils literal notranslate"><span class="pre">0.5</span></code>.</p>
|
||
</aside>
|
||
<aside class="footnote brackets" id="id27" role="doc-footnote">
|
||
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id21">6</a><span class="fn-bracket">]</span></span>
|
||
<p>The <code class="docutils literal notranslate"><span class="pre">%</span></code> operator is also used for string formatting; the same
|
||
precedence applies.</p>
|
||
</aside>
|
||
</aside>
|
||
</section>
|
||
</section>
|
||
|
||
|
||
<div class="clearer"></div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||
<div class="sphinxsidebarwrapper">
|
||
<div>
|
||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||
<ul>
|
||
<li><a class="reference internal" href="#">6. Expressions</a><ul>
|
||
<li><a class="reference internal" href="#arithmetic-conversions">6.1. Arithmetic conversions</a></li>
|
||
<li><a class="reference internal" href="#atoms">6.2. Atoms</a><ul>
|
||
<li><a class="reference internal" href="#built-in-constants">6.2.1. Built-in constants</a></li>
|
||
<li><a class="reference internal" href="#atom-identifiers">6.2.2. Identifiers (Names)</a><ul>
|
||
<li><a class="reference internal" href="#index-5">6.2.2.1. Private name mangling</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#literals">6.2.3. Literals</a><ul>
|
||
<li><a class="reference internal" href="#literals-and-object-identity">6.2.3.1. Literals and object identity</a></li>
|
||
<li><a class="reference internal" href="#string-literal-concatenation">6.2.3.2. String literal concatenation</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#parenthesized-groups">6.2.4. Parenthesized groups</a></li>
|
||
<li><a class="reference internal" href="#container-displays">6.2.5. Container displays</a><ul>
|
||
<li><a class="reference internal" href="#list-displays">6.2.5.1. List displays</a></li>
|
||
<li><a class="reference internal" href="#set-displays">6.2.5.2. Set displays</a></li>
|
||
<li><a class="reference internal" href="#tuple-displays">6.2.5.3. Tuple displays</a></li>
|
||
<li><a class="reference internal" href="#dictionary-displays">6.2.5.4. Dictionary displays</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#comprehensions">6.2.6. Comprehensions</a><ul>
|
||
<li><a class="reference internal" href="#filtering-in-comprehensions">6.2.6.1. Filtering in comprehensions</a></li>
|
||
<li><a class="reference internal" href="#complex-comprehensions">6.2.6.2. Complex comprehensions</a></li>
|
||
<li><a class="reference internal" href="#unpacking-in-comprehensions">6.2.6.3. Unpacking in comprehensions</a></li>
|
||
<li><a class="reference internal" href="#asynchronous-comprehensions">6.2.6.4. Asynchronous comprehensions</a></li>
|
||
<li><a class="reference internal" href="#formal-grammar-for-comprehensions">6.2.6.5. Formal grammar for comprehensions</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#generator-expressions">6.2.7. Generator expressions</a></li>
|
||
<li><a class="reference internal" href="#yield-expressions">6.2.8. Yield expressions</a><ul>
|
||
<li><a class="reference internal" href="#generator-iterator-methods">6.2.8.1. Generator-iterator methods</a></li>
|
||
<li><a class="reference internal" href="#examples">6.2.8.2. Examples</a></li>
|
||
<li><a class="reference internal" href="#asynchronous-generator-functions">6.2.8.3. Asynchronous generator functions</a></li>
|
||
<li><a class="reference internal" href="#asynchronous-generator-iterator-methods">6.2.8.4. Asynchronous generator-iterator methods</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#primaries">6.3. Primaries</a><ul>
|
||
<li><a class="reference internal" href="#attribute-references">6.3.1. Attribute references</a></li>
|
||
<li><a class="reference internal" href="#subscriptions-and-slicings">6.3.2. Subscriptions and slicings</a><ul>
|
||
<li><a class="reference internal" href="#slicings">6.3.2.1. Slicings</a></li>
|
||
<li><a class="reference internal" href="#comma-separated-subscripts">6.3.2.2. Comma-separated subscripts</a></li>
|
||
<li><a class="reference internal" href="#starred-subscriptions">6.3.2.3. “Starred” subscriptions</a></li>
|
||
<li><a class="reference internal" href="#formal-subscription-grammar">6.3.2.4. Formal subscription grammar</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#calls">6.3.3. Calls</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#await-expression">6.4. Await expression</a></li>
|
||
<li><a class="reference internal" href="#the-power-operator">6.5. The power operator</a></li>
|
||
<li><a class="reference internal" href="#unary-arithmetic-and-bitwise-operations">6.6. Unary arithmetic and bitwise operations</a></li>
|
||
<li><a class="reference internal" href="#binary-arithmetic-operations">6.7. Binary arithmetic operations</a></li>
|
||
<li><a class="reference internal" href="#shifting-operations">6.8. Shifting operations</a></li>
|
||
<li><a class="reference internal" href="#binary-bitwise-operations">6.9. Binary bitwise operations</a></li>
|
||
<li><a class="reference internal" href="#comparisons">6.10. Comparisons</a><ul>
|
||
<li><a class="reference internal" href="#value-comparisons">6.10.1. Value comparisons</a></li>
|
||
<li><a class="reference internal" href="#membership-test-operations">6.10.2. Membership test operations</a></li>
|
||
<li><a class="reference internal" href="#is-not">6.10.3. Identity comparisons</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#boolean-operations">6.11. Boolean operations</a></li>
|
||
<li><a class="reference internal" href="#assignment-expressions">6.12. Assignment expressions</a></li>
|
||
<li><a class="reference internal" href="#conditional-expressions">6.13. Conditional expressions</a></li>
|
||
<li><a class="reference internal" href="#lambda">6.14. Lambdas</a></li>
|
||
<li><a class="reference internal" href="#expression-lists">6.15. Expression lists</a><ul>
|
||
<li><a class="reference internal" href="#index-98">6.15.1. Iterable unpacking</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#evaluation-order">6.16. Evaluation order</a></li>
|
||
<li><a class="reference internal" href="#operator-precedence">6.17. Operator precedence</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
|
||
</div>
|
||
<div>
|
||
<h4>Previous topic</h4>
|
||
<p class="topless"><a href="import.html"
|
||
title="previous chapter"><span class="section-number">5. </span>The import system</a></p>
|
||
</div>
|
||
<div>
|
||
<h4>Next topic</h4>
|
||
<p class="topless"><a href="simple_stmts.html"
|
||
title="next chapter"><span class="section-number">7. </span>Simple statements</a></p>
|
||
</div>
|
||
<script>
|
||
document.addEventListener('DOMContentLoaded', () => {
|
||
const title = document.querySelector('meta[property="og:title"]').content;
|
||
const elements = document.querySelectorAll('.improvepage');
|
||
const pageurl = window.location.href.split('?')[0];
|
||
elements.forEach(element => {
|
||
const url = new URL(element.href.split('?')[0].replace("-nojs", ""));
|
||
url.searchParams.set('pagetitle', title);
|
||
url.searchParams.set('pageurl', pageurl);
|
||
url.searchParams.set('pagesource', "reference/expressions.rst");
|
||
element.href = url.toString();
|
||
});
|
||
});
|
||
</script>
|
||
<div role="note" aria-label="source link">
|
||
<h3>This page</h3>
|
||
<ul class="this-page-menu">
|
||
<li><a href="../bugs.html">Report a bug</a></li>
|
||
<li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>
|
||
<li>
|
||
<a href="https://github.com/python/cpython/blob/3.15/Doc/reference/expressions.rst?plain=1"
|
||
rel="nofollow">Show source
|
||
</a>
|
||
</li>
|
||
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div id="sidebarbutton" title="Collapse sidebar">
|
||
<span>«</span>
|
||
</div>
|
||
|
||
</div>
|
||
<div class="clearer"></div>
|
||
</div>
|
||
<div class="related" role="navigation" aria-label="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="simple_stmts.html" title="7. Simple statements"
|
||
>next</a> |</li>
|
||
<li class="right" >
|
||
<a href="import.html" title="5. The import system"
|
||
>previous</a> |</li>
|
||
|
||
<li class="root-icon"><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>
|
||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||
<li class="switchers">
|
||
<div class="language_switcher_placeholder"></div>
|
||
<div class="version_switcher_placeholder"></div>
|
||
</li>
|
||
<li>
|
||
|
||
</li>
|
||
<li id="cpython-language-and-version">
|
||
<a href="../index.html">3.15.0 Documentation</a> »
|
||
</li>
|
||
|
||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> »</li>
|
||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">6. </span>Expressions</a></li>
|
||
<li class="right">
|
||
|
||
|
||
<div class="inline-search" role="search">
|
||
<form class="inline-search" action="../search.html" method="get">
|
||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">
|
||
<input type="submit" value="Go">
|
||
</form>
|
||
</div>
|
||
|
|
||
</li>
|
||
<li class="right">
|
||
<label class="theme-selector-label">
|
||
Theme
|
||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||
<option value="auto" selected>Auto</option>
|
||
<option value="light">Light</option>
|
||
<option value="dark">Dark</option>
|
||
</select>
|
||
</label> |</li>
|
||
|
||
</ul>
|
||
</div>
|
||
<div class="footer">
|
||
© <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.
|
||
<br>
|
||
This page is licensed under the Python Software Foundation License Version 2.
|
||
<br>
|
||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||
<br>
|
||
|
||
See <a href="/license.html">History and License</a> for more information.<br>
|
||
|
||
|
||
<br>
|
||
|
||
The Python Software Foundation is a non-profit corporation.
|
||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||
<br>
|
||
<br>
|
||
Last updated on Oct 09, 2026 (11:35 UTC).
|
||
|
||
<a href="/bugs.html">Found a bug</a>?
|
||
|
||
<br>
|
||
|
||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||
</div>
|
||
|
||
</body>
|
||
</html> |