6.Expressions

This chapter explains the meaning of the elements of expressions in Python.

Syntax Notes: In this and the following chapters, extended BNF notation willbe used to describe syntax, not lexical analysis. When (one alternative of) asyntax rule has the form

name ::= othername

and no semantics are given, the semantics of this form ofname are the sameas forothername.

6.1.Arithmetic conversions

When a description of an arithmetic operator below uses the phrase “the numericarguments are converted to a common type”, this means that the operatorimplementation for built-in types works as follows:

  • If either argument is a complex number, the other is converted to complex;

  • otherwise, if either argument is a floating-point number, the other isconverted to floating point;

  • otherwise, both must be integers and no conversion is necessary.

Some additional rules apply for certain operators (e.g., a string as a leftargument to the ‘%’ operator). Extensions must define their own conversionbehavior.

6.2.Atoms

Atoms are the most basic elements of expressions. The simplest atoms areidentifiers or literals. Forms enclosed in parentheses, brackets or braces arealso categorized syntactically as atoms. The syntax for atoms is:

atom      ::=identifier |literal |enclosureenclosure ::=parenth_form |list_display |dict_display |set_display              |generator_expression |yield_atom

6.2.1.Identifiers (Names)

An identifier occurring as an atom is a name. See sectionIdentifiers and keywordsfor lexical definition and sectionNaming and binding for documentation of naming andbinding.

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 aNameErrorexception.

6.2.1.1.Private name mangling

When an identifier that textually occurs in a class definition begins with twoor more underscore characters and does not end in two or more underscores, itis considered aprivate name of that class.

More precisely, private names are transformed to a longer form before code isgenerated for them. If the transformed name is longer than 255 characters,implementation-defined truncation may happen.

The transformation is independent of the syntactical context in which theidentifier is used but only the following private identifiers are mangled:

  • Any name used as the name of a variable that is assigned or read or anyname of an attribute being accessed.

    The__name__ attribute of nested functions, classes, andtype aliases is however not mangled.

  • The name of imported modules, e.g.,__spam inimport__spam.If the module is part of a package (i.e., its name contains a dot),the name isnot mangled, e.g., the__foo inimport__foo.baris not mangled.

  • The name of an imported member, e.g.,__f infromspamimport__f.

The transformation rule is defined as follows:

  • The class name, with leading underscores removed and a single leadingunderscore inserted, is inserted in front of the identifier, e.g., theidentifier__spam occurring in a class namedFoo,_Foo or__Foo is transformed to_Foo__spam.

  • If the class name consists only of underscores, the transformation is theidentity, e.g., the identifier__spam occurring in a class named_or__ is left as is.

6.2.2.Literals

Python supports string and bytes literals and various numeric literals:

literal ::=stringliteral |bytesliteral            |integer |floatnumber |imagnumber

Evaluation of a literal yields an object of the given type (string, bytes,integer, floating-point number, complex number) with the given value. The valuemay be approximated in the case of floating-point and imaginary (complex)literals. See sectionLiterals for details.

All literals correspond to immutable data types, and hence the object’s identityis less important than its value. Multiple evaluations of literals with thesame value (either the same occurrence in the program text or a differentoccurrence) may obtain the same object or a different object with the samevalue.

6.2.3.Parenthesized forms

A parenthesized form is an optional expression list enclosed in parentheses:

parenth_form ::= "(" [starred_expression] ")"

A parenthesized expression list yields whatever that expression list yields: ifthe list contains at least one comma, it yields a tuple; otherwise, it yieldsthe single expression that makes up the expression list.

An empty pair of parentheses yields an empty tuple object. Since tuples areimmutable, the same rules as for literals apply (i.e., two occurrences of the emptytuple may or may not yield the same object).

Note that tuples are not formed by the parentheses, but rather by use of thecomma. The exception is the empty tuple, for which parenthesesarerequired — allowing unparenthesized “nothing” in expressions would causeambiguities and allow common typos to pass uncaught.

6.2.4.Displays for lists, sets and dictionaries

For constructing a list, a set or a dictionary Python provides special syntaxcalled “displays”, each of them in two flavors:

  • either the container contents are listed explicitly, or

  • they are computed via a set of looping and filtering instructions, called acomprehension.

Common syntax elements for comprehensions are:

comprehension ::=assignment_expressioncomp_forcomp_for      ::= ["async"] "for"target_list "in"or_test [comp_iter]comp_iter     ::=comp_for |comp_ifcomp_if       ::= "if"or_test [comp_iter]

The comprehension consists of a single expression followed by at least onefor clause and zero or morefor orif clauses.In this case, the elements of the new container are those that would be producedby considering each of thefor orif clauses a block,nesting from left to right, and evaluating the expression to produce an elementeach time the innermost block is reached.

However, aside from the iterable expression in the leftmostfor clause,the comprehension is executed in a separate implicitly nested scope. This ensuresthat names assigned to in the target list don’t “leak” into the enclosing scope.

The iterable expression in the leftmostfor clause is evaluateddirectly in the enclosing scope and then passed as an argument to the implicitlynested scope. Subsequentfor clauses and any filter condition in theleftmostfor clause cannot be evaluated in the enclosing scope asthey may depend on the values obtained from the leftmost iterable. For example:[x*yforxinrange(10)foryinrange(x,x+10)].

To ensure the comprehension always results in a container of the appropriatetype,yield andyieldfrom expressions are prohibited in the implicitlynested scope.

Since Python 3.6, in anasyncdef function, anasyncforclause may be used to iterate over aasynchronous iterator.A comprehension in anasyncdef function may consist of either afor orasyncfor clause following the leadingexpression, may contain additionalfor orasyncforclauses, and may also useawait expressions.

If a comprehension containsasyncfor clauses, or if it containsawait expressions or other asynchronous comprehensions anywhere exceptthe iterable expression in the leftmostfor clause, it is called anasynchronous comprehension. An asynchronous comprehension may suspend theexecution of the coroutine function in which it appears.See alsoPEP 530.

Added in version 3.6:Asynchronous comprehensions were introduced.

Changed in version 3.8:yield andyieldfrom prohibited in the implicitly nested scope.

Changed in version 3.11:Asynchronous comprehensions are now allowed inside comprehensions inasynchronous functions. Outer comprehensions implicitly becomeasynchronous.

6.2.5.List displays

A list display is a possibly empty series of expressions enclosed in squarebrackets:

list_display ::= "[" [flexible_expression_list |comprehension] "]"

A list display yields a new list object, the contents being specified by eithera list of expressions or a comprehension. When a comma-separated list ofexpressions is supplied, its elements are evaluated from left to right andplaced into the list object in that order. When a comprehension is supplied,the list is constructed from the elements resulting from the comprehension.

6.2.6.Set displays

A set display is denoted by curly braces and distinguishable from dictionarydisplays by the lack of colons separating keys and values:

set_display ::= "{" (flexible_expression_list |comprehension) "}"

A set display yields a new mutable set object, the contents being specified byeither a sequence of expressions or a comprehension. When a comma-separatedlist of expressions is supplied, its elements are evaluated from left to rightand added to the set object. When a comprehension is supplied, the set isconstructed from the elements resulting from the comprehension.

An empty set cannot be constructed with{}; this literal constructs an emptydictionary.

6.2.7.Dictionary displays

A dictionary display is a possibly empty series of dict items (key/value pairs)enclosed in curly braces:

dict_display       ::= "{" [dict_item_list |dict_comprehension] "}"dict_item_list     ::=dict_item (","dict_item)* [","]dict_item          ::=expression ":"expression | "**"or_exprdict_comprehension ::=expression ":"expressioncomp_for

A dictionary display yields a new dictionary object.

If a comma-separated sequence of dict items is given, they are evaluatedfrom left to right to define the entries of the dictionary: each key object isused as a key into the dictionary to store the corresponding value. This meansthat you can specify the same key multiple times in the dict item list, and thefinal dictionary’s value for that key will be the last one given.

A double asterisk** denotesdictionary unpacking.Its operand must be amapping. Each mapping item is addedto the new dictionary. Later values replace values already set byearlier dict items and earlier dictionary unpackings.

Added in version 3.5:Unpacking into dictionary displays, originally proposed byPEP 448.

A dict comprehension, in contrast to list and set comprehensions, needs twoexpressions separated with a colon followed by the usual “for” and “if” clauses.When the comprehension is run, the resulting key and value elements are insertedin the new dictionary in the order they are produced.

Restrictions on the types of the key values are listed earlier in sectionThe standard type hierarchy. (To summarize, the key type should behashable, which excludesall mutable objects.) Clashes between duplicate keys are not detected; the lastvalue (textually rightmost in the display) stored for a given key valueprevails.

Changed in version 3.8:Prior to Python 3.8, in dict comprehensions, the evaluation order of keyand value was not well-defined. In CPython, the value was evaluated beforethe key. Starting with 3.8, the key is evaluated before the value, asproposed byPEP 572.

6.2.8.Generator expressions

A generator expression is a compact generator notation in parentheses:

generator_expression ::= "("expressioncomp_for ")"

A generator expression yields a new generator object. Its syntax is the same asfor comprehensions, except that it is enclosed in parentheses instead ofbrackets or curly braces.

Variables used in the generator expression are evaluated lazily when the__next__() method is called for the generator object (in the samefashion as normal generators). However, the iterable expression in theleftmostfor clause is immediately evaluated, so that an errorproduced by it will be emitted at the point where the generator expressionis defined, rather than at the point where the first value is retrieved.Subsequentfor clauses and any filter condition in the leftmostfor clause cannot be evaluated in the enclosing scope as they maydepend on the values obtained from the leftmost iterable. For example:(x*yforxinrange(10)foryinrange(x,x+10)).

The parentheses can be omitted on calls with only one argument. See sectionCalls for details.

To avoid interfering with the expected operation of the generator expressionitself,yield andyieldfrom expressions are prohibited in theimplicitly defined generator.

If a generator expression contains eitherasyncforclauses orawait expressions it is called anasynchronous generator expression. An asynchronous generatorexpression returns a new asynchronous generator object,which is an asynchronous iterator (seeAsynchronous Iterators).

Added in version 3.6:Asynchronous generator expressions were introduced.

Changed in version 3.7:Prior to Python 3.7, asynchronous generator expressions couldonly appear inasyncdef coroutines. Startingwith 3.7, any function can use asynchronous generator expressions.

Changed in version 3.8:yield andyieldfrom prohibited in the implicitly nested scope.

6.2.9.Yield expressions

yield_atom       ::= "("yield_expression ")"yield_from       ::= "yield" "from"expressionyield_expression ::= "yield"yield_list |yield_from

The yield expression is used when defining agenerator functionor anasynchronous generator function andthus can only be used in the body of a function definition. Using a yieldexpression in a function’s body causes that function to be a generator function,and using it in anasyncdef function’s body causes thatcoroutine function to be an asynchronous generator function. For example:

defgen():# defines a generator functionyield123asyncdefagen():# defines an asynchronous generator functionyield123

Due to their side effects on the containing scope,yield expressionsare not permitted as part of the implicitly defined scopes used toimplement comprehensions and generator expressions.

Changed in version 3.8:Yield expressions prohibited in the implicitly nested scopes used toimplement comprehensions and generator expressions.

Generator functions are described below, while asynchronous generatorfunctions are described separately in sectionAsynchronous generator functions.

When a generator function is called, it returns an iterator known as agenerator. That generator then controls the execution of the generatorfunction. 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 issuspended again, returning the value ofyield_listto the generator’s caller,orNone ifyield_list is omitted.By suspended, we mean that all local state isretained, including the current bindings of local variables, the instructionpointer, the internal evaluation stack, and the state of any exception handling.When the execution is resumed by calling one of the generator’s methods, thefunction can proceed exactly as if the yield expression were just anotherexternal call. The value of the yield expression after resuming depends on themethod which resumed the execution. If__next__() is used(typically via either afor or thenext() builtin) then theresult isNone. Otherwise, ifsend() is used, thenthe result will be the value passed in to that method.

All of this makes generator functions quite similar to coroutines; they yieldmultiple times, they have more than one entry point and their execution can besuspended. The only difference is that a generator function cannot controlwhere the execution should continue after it yields; the control is alwaystransferred to the generator’s caller.

Yield expressions are allowed anywhere in atry construct. If thegenerator is not resumed before it isfinalized (by reaching a zero reference count or by being garbage collected),the generator-iterator’sclose() method will be called,allowing any pendingfinally clauses to execute.

Whenyieldfrom<expr> is used, the supplied expression must be aniterable. The values produced by iterating that iterable are passed directlyto the caller of the current generator’s methods. Any values passed in withsend() and any exceptions passed in withthrow() are passed to the underlying iterator if it has theappropriate methods. If this is not the case, thensend()will raiseAttributeError orTypeError, whilethrow() will just raise the passed in exception immediately.

When the underlying iterator is complete, thevalueattribute of the raisedStopIteration instance becomes the value ofthe yield expression. It can be either set explicitly when raisingStopIteration, or automatically when the subiterator is a generator(by returning a value from the subgenerator).

Changed in version 3.3:Addedyieldfrom<expr> to delegate control flow to a subiterator.

The parentheses may be omitted when the yield expression is the sole expressionon the right hand side of an assignment statement.

See also

PEP 255 - Simple Generators

The proposal for adding generators and theyield statement to Python.

PEP 342 - Coroutines via Enhanced Generators

The proposal to enhance the API and syntax of generators, making themusable as simple coroutines.

PEP 380 - Syntax for Delegating to a Subgenerator

The proposal to introduce theyield_from syntax,making delegation to subgenerators easy.

PEP 525 - Asynchronous Generators

The proposal that expanded onPEP 492 by adding generator capabilities tocoroutine functions.

6.2.9.1.Generator-iterator methods

This subsection describes the methods of a generator iterator. They canbe used to control the execution of a generator function.

Note that calling any of the generator methods below when the generatoris already executing raises aValueError exception.

generator.__next__()

Starts the execution of a generator function or resumes it at the lastexecuted yield expression. When a generator function is resumed with a__next__() method, the current yield expression alwaysevaluates toNone. The execution then continues to the next yieldexpression, where the generator is suspended again, and the value of theyield_list is returned to__next__()’scaller. If the generator exits without yielding another value, aStopIteration exception is raised.

This method is normally called implicitly, e.g. by afor loop, orby the built-innext() function.

generator.send(value)

Resumes the execution and “sends” a value into the generator function. Thevalue argument becomes the result of the current yield expression. Thesend() method returns the next value yielded by the generator, orraisesStopIteration if the generator exits without yielding anothervalue. Whensend() is called to start the generator, it must be calledwithNone as the argument, because there is no yield expression thatcould receive the value.

generator.throw(value)
generator.throw(type[,value[,traceback]])

Raises an exception at the point where the generator was paused,and returns the next value yielded by the generator function. If the generatorexits without yielding another value, aStopIteration exception israised. If the generator function does not catch the passed-in exception, orraises a different exception, then that exception propagates to the caller.

In typical use, this is called with a single exception instance similar to theway theraise keyword is used.

For backwards compatibility, however, the second signature issupported, following a convention from older versions of Python.Thetype argument should be an exception class, andvalueshould be an exception instance. If thevalue is not provided, thetype constructor is called to get an instance. Iftracebackis provided, it is set on the exception, otherwise any existing__traceback__ attribute stored invalue maybe cleared.

Changed in version 3.12:The second signature (type[, value[, traceback]]) is deprecated andmay be removed in a future version of Python.

generator.close()

Raises aGeneratorExit at the point where the generator function waspaused. If the generator function catches the exception and returns avalue, this value is returned fromclose(). If the generator functionis already closed, or raisesGeneratorExit (by not catching theexception),close() returnsNone. If the generator yields avalue, aRuntimeError is raised. If the generator raises any otherexception, it is propagated to the caller. If the generator has alreadyexited due to an exception or normal exit,close() returnsNone and has no other effect.

Changed in version 3.13:If a generator returns a value upon being closed, the value is returnedbyclose().

6.2.9.2.Examples

Here is a simple example that demonstrates the behavior of generators andgenerator functions:

>>>defecho(value=None):...print("Execution starts when 'next()' is called for the first time.")...try:...whileTrue:...try:...value=(yieldvalue)...exceptExceptionase:...value=e...finally:...print("Don't forget to clean up when 'close()' is called.")...>>>generator=echo(1)>>>print(next(generator))Execution starts when 'next()' is called for the first time.1>>>print(next(generator))None>>>print(generator.send(2))2>>>generator.throw(TypeError,"spam")TypeError('spam',)>>>generator.close()Don't forget to clean up when 'close()' is called.

For examples usingyieldfrom, seePEP 380: Syntax for Delegating to a Subgenerator in “What’s New inPython.”

6.2.9.3.Asynchronous generator functions

The presence of a yield expression in a function or method defined usingasyncdef further defines the function as anasynchronous generator function.

When an asynchronous generator function is called, it returns anasynchronous 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 anasyncfor statement in a coroutine function analogously tohow a generator object would be used in afor statement.

Calling one of the asynchronous generator’s methods returns anawaitableobject, and the execution starts when this object is awaited on. At that time,the execution proceeds to the first yield expression, where it is suspendedagain, returning the value ofyield_list to theawaiting coroutine. As with a generator, suspension means that all local stateis retained, including the current bindings of local variables, the instructionpointer, the internal evaluation stack, and the state of any exception handling.When the execution is resumed by awaiting on the next object returned by theasynchronous generator’s methods, the function can proceed exactly as if theyield expression were just another external call. The value of the yieldexpression after resuming depends on the method which resumed the execution. If__anext__() is used then the result isNone. Otherwise, ifasend() is used, then the result will be the value passed in to thatmethod.

If an asynchronous generator happens to exit early bybreak, the callertask being cancelled, or other exceptions, the generator’s async cleanup codewill run and possibly raise exceptions or access context variables in anunexpected context–perhaps after the lifetime of tasks it depends, orduring the event loop shutdown when the async-generator garbage collection hookis called.To prevent this, the caller must explicitly close the async generator by callingaclose() method to finalize the generator and ultimately detach itfrom the event loop.

In an asynchronous generator function, yield expressions are allowed anywherein atry construct. However, if an asynchronous generator is notresumed before it is finalized (by reaching a zero reference count or bybeing garbage collected), then a yield expression within atryconstruct could result in a failure to execute pendingfinallyclauses. In this case, it is the responsibility of the event loop orscheduler running the asynchronous generator to call the asynchronousgenerator-iterator’saclose() method and run the resultingcoroutine object, thus allowing any pendingfinally clausesto execute.

To take care of finalization upon event loop termination, an event loop shoulddefine afinalizer function which takes an asynchronous generator-iterator andpresumably callsaclose() and executes the coroutine.Thisfinalizer may be registered by callingsys.set_asyncgen_hooks().When first iterated over, an asynchronous generator-iterator will store theregisteredfinalizer to be called upon finalization. For a reference exampleof afinalizer method see the implementation ofasyncio.Loop.shutdown_asyncgens inLib/asyncio/base_events.py.

The expressionyieldfrom<expr> is a syntax error when used in anasynchronous generator function.

6.2.9.4.Asynchronous generator-iterator methods

This subsection describes the methods of an asynchronous generator iterator,which are used to control the execution of a generator function.

asyncagen.__anext__()

Returns an awaitable which when run starts to execute the asynchronousgenerator or resumes it at the last executed yield expression. When anasynchronous generator function is resumed with an__anext__()method, the current yield expression always evaluates toNone in thereturned awaitable, which when run will continue to the next yieldexpression. The value of theyield_list of theyield expression is the value of theStopIteration exception raised bythe completing coroutine. If the asynchronous generator exits withoutyielding another value, the awaitable instead raises aStopAsyncIteration exception, signalling that the asynchronousiteration has completed.

This method is normally called implicitly by aasyncfor loop.

asyncagen.asend(value)

Returns an awaitable which when run resumes the execution of theasynchronous generator. As with thesend() method for agenerator, this “sends” a value into the asynchronous generator function,and thevalue argument becomes the result of the current yield expression.The awaitable returned by theasend() method will return the nextvalue yielded by the generator as the value of the raisedStopIteration, or raisesStopAsyncIteration if theasynchronous generator exits without yielding another value. Whenasend() is called to start the asynchronousgenerator, it must be called withNone as the argument,because there is no yield expression that could receive the value.

asyncagen.athrow(value)
asyncagen.athrow(type[,value[,traceback]])

Returns an awaitable that raises an exception of typetype at the pointwhere the asynchronous generator was paused, and returns the next valueyielded by the generator function as the value of the raisedStopIteration exception. If the asynchronous generator exitswithout yielding another value, aStopAsyncIteration exception israised by the awaitable.If the generator function does not catch the passed-in exception, orraises a different exception, then when the awaitable is run that exceptionpropagates to the caller of the awaitable.

Changed in version 3.12:The second signature (type[, value[, traceback]]) is deprecated andmay be removed in a future version of Python.

asyncagen.aclose()

Returns an awaitable that when run will throw aGeneratorExit intothe asynchronous generator function at the point where it was paused.If the asynchronous generator function then exits gracefully, is alreadyclosed, or raisesGeneratorExit (by not catching the exception),then the returned awaitable will raise aStopIteration exception.Any further awaitables returned by subsequent calls to the asynchronousgenerator will raise aStopAsyncIteration exception. If theasynchronous generator yields a value, aRuntimeError is raisedby the awaitable. If the asynchronous generator raises any other exception,it is propagated to the caller of the awaitable. If the asynchronousgenerator has already exited due to an exception or normal exit, thenfurther calls toaclose() will return an awaitable that does nothing.

6.3.Primaries

Primaries represent the most tightly bound operations of the language. Theirsyntax is:

primary ::=atom |attributeref |subscription |slicing |call

6.3.1.Attribute references

An attribute reference is a primary followed by a period and a name:

attributeref ::=primary "."identifier

The primary must evaluate to an object of a type that supports attributereferences, which most objects do. This object is then asked to produce theattribute whose name is the identifier. The type and value produced isdetermined by the object. Multiple evaluations of the same attributereference may yield different objects.

This production can be customized by overriding the__getattribute__() method or the__getattr__()method. The__getattribute__() method is called first and eitherreturns a value or raisesAttributeError if the attribute is notavailable.

If anAttributeError is raised and the object has a__getattr__()method, that method is called as a fallback.

6.3.2.Subscriptions

The subscription of an instance of acontainer classwill generally select an element from the container. The subscription of ageneric class will generally return aGenericAlias object.

subscription ::=primary "["flexible_expression_list "]"

When an object is subscripted, the interpreter will evaluate the primary andthe expression list.

The primary must evaluate to an object that supports subscription. An objectmay support subscription through defining one or both of__getitem__() and__class_getitem__(). When theprimary is subscripted, the evaluated result of the expression list will bepassed to one of these methods. For more details on when__class_getitem__is called instead of__getitem__, see__class_getitem__ versus __getitem__.

If the expression list contains at least one comma, or if any of the expressionsare starred, the expression list will evaluate to atuple containingthe items of the expression list. Otherwise, the expression list will evaluateto the value of the list’s sole member.

Changed in version 3.11:Expressions in an expression list may be starred. SeePEP 646.

For built-in objects, there are two types of objects that support subscriptionvia__getitem__():

  1. Mappings. If the primary is amapping, the expression list mustevaluate to an object whose value is one of the keys of the mapping, and thesubscription selects the value in the mapping that corresponds to that key.An example of a builtin mapping class is thedict class.

  2. Sequences. If the primary is asequence, the expression list mustevaluate to anint or aslice (as discussed in thefollowing section). Examples of builtin sequence classes include thestr,list andtuple classes.

The formal syntax makes no special provision for negative indices insequences. However, built-in sequences all provide a__getitem__()method that interprets negative indices by adding the length of the sequenceto the index so that, for example,x[-1] selects the last item ofx. Theresulting value must be a nonnegative integer less than the number of items inthe sequence, and the subscription selects the item whose index is that value(counting from zero). Since the support for negative indices and slicingoccurs in the object’s__getitem__() method, subclasses overridingthis method will need to explicitly add that support.

Astring is a special kind of sequence whose items arecharacters. A character is not a separate data type but astring of exactly one character.

6.3.3.Slicings

A slicing selects a range of items in a sequence object (e.g., a string, tupleor list). Slicings may be used as expressions or as targets in assignment ordel statements. The syntax for a slicing:

slicing      ::=primary "["slice_list "]"slice_list   ::=slice_item (","slice_item)* [","]slice_item   ::=expression |proper_sliceproper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]lower_bound  ::=expressionupper_bound  ::=expressionstride       ::=expression

There is ambiguity in the formal syntax here: anything that looks like anexpression list also looks like a slice list, so any subscription can beinterpreted as a slicing. Rather than further complicating the syntax, this isdisambiguated by defining that in this case the interpretation as a subscriptiontakes priority over the interpretation as a slicing (this is the case if theslice list contains no proper slice).

The semantics for a slicing are as follows. The primary is indexed (using thesame__getitem__() method asnormal subscription) with a key that is constructed from the slice list, asfollows. If the slice list contains at least one comma, the key is a tuplecontaining the conversion of the slice items; otherwise, the conversion of thelone slice item is the key. The conversion of a slice item that is anexpression is that expression. The conversion of a proper slice is a sliceobject (see sectionThe standard type hierarchy) whosestart,stop andstep attributes are the values of theexpressions given as lower bound, upper bound and stride, respectively,substitutingNone for missing expressions.

6.3.4.Calls

A call calls a callable object (e.g., afunction) with a possibly emptyseries ofarguments:

call                 ::=primary "(" [argument_list [","] |comprehension] ")"argument_list        ::=positional_arguments [","starred_and_keywords]                         [","keywords_arguments]                         |starred_and_keywords [","keywords_arguments]                         |keywords_argumentspositional_arguments ::= positional_item ("," positional_item)*positional_item      ::=assignment_expression | "*"expressionstarred_and_keywords ::= ("*"expression |keyword_item)                         ("," "*"expression | ","keyword_item)*keywords_arguments   ::= (keyword_item | "**"expression)                         (","keyword_item | "," "**"expression)*keyword_item         ::=identifier "="expression

An optional trailing comma may be present after the positional and keyword argumentsbut does not affect the semantics.

The primary must evaluate to a callable object (user-defined functions, built-infunctions, methods of built-in objects, class objects, methods of classinstances, and all objects having a__call__() method are callable). Allargument expressions are evaluated before the call is attempted. Please referto sectionFunction definitions for the syntax of formalparameter lists.

If keyword arguments are present, they are first converted to positionalarguments, as follows. First, a list of unfilled slots is created for theformal parameters. If there are N positional arguments, they are placed in thefirst N slots. Next, for each keyword argument, the identifier is used todetermine the corresponding slot (if the identifier is the same as the firstformal parameter name, the first slot is used, and so on). If the slot isalready filled, aTypeError exception is raised. Otherwise, theargument is placed in the slot, filling it (even if the expression isNone, it fills the slot). When all arguments have been processed, the slotsthat are still unfilled are filled with the corresponding default value from thefunction definition. (Default values are calculated, once, when the function isdefined; thus, a mutable object such as a list or dictionary used as defaultvalue will be shared by all calls that don’t specify an argument value for thecorresponding slot; this should usually be avoided.) If there are any unfilledslots for which no default value is specified, aTypeError exception israised. Otherwise, the list of filled slots is used as the argument list forthe call.

CPython implementation detail: An implementation may provide built-in functions whose positional parametersdo 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 thecase for functions implemented in C that usePyArg_ParseTuple() toparse their arguments.

If there are more positional arguments than there are formal parameter slots, aTypeError exception is raised, unless a formal parameter using the syntax*identifier is present; in this case, that formal parameter receives a tuplecontaining the excess positional arguments (or an empty tuple if there were noexcess positional arguments).

If any keyword argument does not correspond to a formal parameter name, aTypeError exception is raised, unless a formal parameter using the syntax**identifier is present; in this case, that formal parameter receives adictionary containing the excess keyword arguments (using the keywords as keysand the argument values as corresponding values), or a (new) empty dictionary ifthere were no excess keyword arguments.

If the syntax*expression appears in the function call,expression mustevaluate to aniterable. Elements from these iterables aretreated as if they were additional positional arguments. For the callf(x1,x2,*y,x3,x4), ify evaluates to a sequencey1, …,yM,this is equivalent to a call with M+4 positional argumentsx1,x2,y1, …,yM,x3,x4.

A consequence of this is that although the*expression syntax may appearafter explicit keyword arguments, it is processedbefore thekeyword arguments (and any**expression arguments – see below). So:

>>>deff(a,b):...print(a,b)...>>>f(b=1,*(2,))2 1>>>f(a=1,*(2,))Traceback (most recent call last):  File"<stdin>", line1, in<module>TypeError:f() got multiple values for keyword argument 'a'>>>f(1,*(2,))1 2

It is unusual for both keyword arguments and the*expression syntax to beused in the same call, so in practice this confusion does not often arise.

If the syntax**expression appears in the function call,expression mustevaluate to amapping, the contents of which are treated asadditional keyword arguments. If a parameter matching a key has already beengiven a value (by an explicit keyword argument, or from another unpacking),aTypeError exception is raised.

When**expression is used, each key in this mapping must bea string.Each value from the mapping is assigned to the first formal parametereligible for keyword assignment whose name is equal to the key.A key need not be a Python identifier (e.g."max-temp°F" is acceptable,although it will not match any formal parameter that could be declared).If there is no match to a formal parameterthe key-value pair is collected by the** parameter, if there is one,or if there is not, aTypeError exception is raised.

Formal parameters using the syntax*identifier or**identifier cannot beused as positional argument slots or as keyword argument names.

Changed in version 3.5:Function calls accept any number of* and** unpackings,positional arguments may follow iterable unpackings (*),and keyword arguments may follow dictionary unpackings (**).Originally proposed byPEP 448.

A call always returns some value, possiblyNone, unless it raises anexception. How this value is computed depends on the type of the callableobject.

If it is—

a user-defined function:

The code block for the function is executed, passing it the argument list. Thefirst thing the code block will do is bind the formal parameters to thearguments; this is described in sectionFunction definitions. When the code blockexecutes areturn statement, this specifies the return value of thefunction call. If execution reaches the end of the code block withoutexecuting areturn statement, the return value isNone.

a built-in function or method:

The result is up to the interpreter; seeBuilt-in Functions for thedescriptions of built-in functions and methods.

a class object:

A new instance of that class is returned.

a class instance method:

The corresponding user-defined function is called, with an argument list that isone longer than the argument list of the call: the instance becomes the firstargument.

a class instance:

The class must define a__call__() method; the effect is then the same asif that method was called.

6.4.Await expression

Suspend the execution ofcoroutine on anawaitable object.Can only be used inside acoroutine function.

await_expr ::= "await"primary

Added in version 3.5.

6.5.The power operator

The power operator binds more tightly than unary operators on its left; it bindsless tightly than unary operators on its right. The syntax is:

power ::= (await_expr |primary) ["**"u_expr]

Thus, in an unparenthesized sequence of power and unary operators, the operatorsare evaluated from right to left (this does not constrain the evaluation orderfor the operands):-1**2 results in-1.

The power operator has the same semantics as the built-inpow() function,when called with two arguments: it yields its left argument raised to the powerof its right argument. The numeric arguments are first converted to a commontype, and the result is of that type.

For int operands, the result has the same type as the operands unless the secondargument is negative; in that case, all arguments are converted to float and afloat result is delivered. For example,10**2 returns100, but10**-2 returns0.01.

Raising0.0 to a negative power results in aZeroDivisionError.Raising a negative number to a fractional power results in acomplexnumber. (In earlier versions it raised aValueError.)

This operation can be customized using the special__pow__() and__rpow__() methods.

6.6.Unary arithmetic and bitwise operations

All unary arithmetic and bitwise operations have the same priority:

u_expr ::=power | "-"u_expr | "+"u_expr | "~"u_expr

The unary- (minus) operator yields the negation of its numeric argument; theoperation can be overridden with the__neg__() special method.

The unary+ (plus) operator yields its numeric argument unchanged; theoperation can be overridden with the__pos__() special method.

The unary~ (invert) operator yields the bitwise inversion of its integerargument. The bitwise inversion ofx is defined as-(x+1). It onlyapplies to integral numbers or to custom objects that override the__invert__() special method.

In all three cases, if the argument does not have the proper type, aTypeError exception is raised.

6.7.Binary arithmetic operations

The binary arithmetic operations have the conventional priority levels. Notethat some of these operations also apply to certain non-numeric types. Apartfrom the power operator, there are only two levels, one for multiplicativeoperators and one for additive operators:

m_expr ::=u_expr |m_expr "*"u_expr |m_expr "@"m_expr |m_expr "//"u_expr |m_expr "/"u_expr |m_expr "%"u_expra_expr ::=m_expr |a_expr "+"m_expr |a_expr "-"m_expr

The* (multiplication) operator yields the product of its arguments. Thearguments must either both be numbers, or one argument must be an integer andthe other must be a sequence. In the former case, the numbers are converted to acommon type and then multiplied together. In the latter case, sequencerepetition is performed; a negative repetition factor yields an empty sequence.

This operation can be customized using the special__mul__() and__rmul__() methods.

The@ (at) operator is intended to be used for matrix multiplication. Nobuiltin Python types implement this operator.

This operation can be customized using the special__matmul__() and__rmatmul__() methods.

Added in version 3.5.

The/ (division) and// (floor division) operators yield the quotient oftheir arguments. The numeric arguments are first converted to a common type.Division of integers yields a float, while floor division of integers results in aninteger; the result is that of mathematical division with the ‘floor’ functionapplied to the result. Division by zero raises theZeroDivisionErrorexception.

The division operation can be customized using the special__truediv__()and__rtruediv__() methods.The floor division operation can be customized using the special__floordiv__() and__rfloordiv__() methods.

The% (modulo) operator yields the remainder from the division of the firstargument by the second. The numeric arguments are first converted to a commontype. A zero right argument raises theZeroDivisionError exception. Thearguments may be floating-point numbers, e.g.,3.14%0.7 equals0.34(since3.14 equals4*0.7+0.34.) The modulo operator always yields aresult with the same sign as its second operand (or zero); the absolute value ofthe result is strictly smaller than the absolute value of the second operand[1].

The floor division and modulo operators are connected by the followingidentity:x==(x//y)*y+(x%y). Floor division and modulo are alsoconnected with the built-in functiondivmod():divmod(x,y)==(x//y,x%y).[2].

In addition to performing the modulo operation on numbers, the% operator isalso overloaded by string objects to perform old-style string formatting (alsoknown as interpolation). The syntax for string formatting is described in thePython Library Reference, sectionprintf-style String Formatting.

Themodulo operation can be customized using the special__mod__()and__rmod__() methods.

The floor division operator, the modulo operator, and thedivmod()function are not defined for complex numbers. Instead, convert to afloating-point number using theabs() function if appropriate.

The+ (addition) operator yields the sum of its arguments. The argumentsmust either both be numbers or both be sequences of the same type. In theformer case, the numbers are converted to a common type and then added together.In the latter case, the sequences are concatenated.

This operation can be customized using the special__add__() and__radd__() methods.

The- (subtraction) operator yields the difference of its arguments. Thenumeric arguments are first converted to a common type.

This operation can be customized using the special__sub__() and__rsub__() methods.

6.8.Shifting operations

The shifting operations have lower priority than the arithmetic operations:

shift_expr ::=a_expr |shift_expr ("<<" | ">>")a_expr

These operators accept integers as arguments. They shift the first argument tothe left or right by the number of bits given by the second argument.

The left shift operation can be customized using the special__lshift__()and__rlshift__() methods.The right shift operation can be customized using the special__rshift__()and__rrshift__() methods.

A right shift byn bits is defined as floor division bypow(2,n). A leftshift byn bits is defined as multiplication withpow(2,n).

6.9.Binary bitwise operations

Each of the three bitwise operations has a different priority level:

and_expr ::=shift_expr |and_expr "&"shift_exprxor_expr ::=and_expr |xor_expr "^"and_expror_expr  ::=xor_expr |or_expr "|"xor_expr

The& operator yields the bitwise AND of its arguments, which must beintegers or one of them must be a custom object overriding__and__() or__rand__() special methods.

The^ operator yields the bitwise XOR (exclusive OR) of its arguments, whichmust be integers or one of them must be a custom object overriding__xor__() or__rxor__() special methods.

The| operator yields the bitwise (inclusive) OR of its arguments, whichmust be integers or one of them must be a custom object overriding__or__() or__ror__() special methods.

6.10.Comparisons

Unlike C, all comparison operations in Python have the same priority, which islower than that of any arithmetic, shifting or bitwise operation. Also unlikeC, expressions likea<b<c have the interpretation that is conventionalin mathematics:

comparison    ::=or_expr (comp_operatoror_expr)*comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="                  | "is" ["not"] | ["not"] "in"

Comparisons yield boolean values:True orFalse. Customrich comparison methods may return non-boolean values. In this casePython will callbool() on such value in boolean contexts.

Comparisons can be chained arbitrarily, e.g.,x<y<=z is equivalent tox<yandy<=z, except thaty is evaluated only once (but in bothcasesz is not evaluated at all whenx<y is found to be false).

Formally, ifa,b,c, …,y,z are expressions andop1,op2, …,opN are comparison operators, thenaop1bop2c...yopNz is equivalenttoaop1bandbop2cand...yopNz, except that each expression isevaluated at most once.

Note thataop1bop2c doesn’t imply any kind of comparison betweena andc, so that, e.g.,x<y>z is perfectly legal (though perhaps notpretty).

6.10.1.Value comparisons

The operators<,>,==,>=,<=, and!= compare thevalues of two objects. The objects do not need to have the same type.

ChapterObjects, values and types states that objects have a value (in addition to typeand 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 aparticular way, e.g. comprised of all its data attributes. Comparison operatorsimplement a particular notion of what the value of an object is. One can thinkof them as defining the value of an object indirectly, by means of theircomparison implementation.

Because all types are (direct or indirect) subtypes ofobject, theyinherit the default comparison behavior fromobject. Types cancustomize their comparison behavior by implementingrich comparison methods like__lt__(), described inBasic customization.

The default behavior for equality comparison (== and!=) is based onthe identity of the objects. Hence, equality comparison of instances with thesame identity results in equality, and equality comparison of instances withdifferent identities results in inequality. A motivation for this defaultbehavior is the desire that all objects should be reflexive (i.e.xisyimpliesx==y).

A default order comparison (<,>,<=, and>=) is not provided;an attempt raisesTypeError. A motivation for this default behavior isthe lack of a similar invariant as for equality.

The behavior of the default equality comparison, that instances with differentidentities are always unequal, may be in contrast to what types will need thathave a sensible definition of object value and value-based equality. Suchtypes will need to customize their comparison behavior, and in fact, a numberof built-in types have done that.

The following list describes the comparison behavior of the most importantbuilt-in types.

  • Numbers of built-in numeric types (Numeric Types — int, float, complex) and of the standardlibrary typesfractions.Fraction anddecimal.Decimal can becompared within and across their types, with the restriction that complexnumbers do not support order comparison. Within the limits of the typesinvolved, they compare mathematically (algorithmically) correct without lossof precision.

    The not-a-number valuesfloat('NaN') anddecimal.Decimal('NaN') arespecial. 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 tothemselves. For example, ifx=float('NaN'),3<x,x<3 andx==x are all false, whilex!=x is true. This behavior iscompliant with IEEE 754.

  • None andNotImplemented are singletons.PEP 8 advises thatcomparisons for singletons should always be done withis orisnot,never the equality operators.

  • Binary sequences (instances ofbytes orbytearray) can becompared within and across their types. They compare lexicographically usingthe numeric values of their elements.

  • Strings (instances ofstr) compare lexicographically using thenumerical Unicode code points (the result of the built-in functionord()) of their characters.[3]

    Strings and binary sequences cannot be directly compared.

  • Sequences (instances oftuple,list, orrange) canbe compared only within each of their types, with the restriction that rangesdo not support order comparison. Equality comparison across these typesresults in inequality, and ordering comparison across these types raisesTypeError.

    Sequences compare lexicographically using comparison of correspondingelements. The built-in containers typically assume identical objects areequal to themselves. That lets them bypass equality tests for identicalobjects to improve performance and to maintain their internal invariants.

    Lexicographical comparison between built-in collections works as follows:

    • For two collections to compare equal, they must be of the same type, havethe same length, and each pair of corresponding elements must compareequal (for example,[1,2]==(1,2) is false because the type is not thesame).

    • Collections that support order comparison are ordered the same as theirfirst unequal elements (for example,[1,2,x]<=[1,2,y] has the samevalue asx<=y). If a corresponding element does not exist, theshorter collection is ordered first (for example,[1,2]<[1,2,3] istrue).

  • Mappings (instances ofdict) compare equal if and only if they haveequal(key,value) pairs. Equality comparison of the keys and valuesenforces reflexivity.

    Order comparisons (<,>,<=, and>=) raiseTypeError.

  • Sets (instances ofset orfrozenset) can be compared withinand across their types.

    They define ordercomparison operators to mean subset and superset tests. Those relations donot define total orderings (for example, the two sets{1,2} and{2,3}are not equal, nor subsets of one another, nor supersets of oneanother). Accordingly, sets are not appropriate arguments for functionswhich depend on total ordering (for example,min(),max(), andsorted() produce undefined results given a list of sets as inputs).

    Comparison of sets enforces reflexivity of its elements.

  • Most other built-in types have no comparison methods implemented, so theyinherit the default comparison behavior.

User-defined classes that customize their comparison behavior should followsome consistency rules, if possible:

  • Equality comparison should be reflexive.In other words, identical objects should compare equal:

    xisy impliesx==y

  • Comparison should be symmetric.In other words, the following expressions should have the same result:

    x==y andy==x

    x!=y andy!=x

    x<y andy>x

    x<=y andy>=x

  • Comparison should be transitive.The following (non-exhaustive) examples illustrate that:

    x>yandy>z impliesx>z

    x<yandy<=z impliesx<z

  • Inverse comparison should result in the boolean negation.In other words, the following expressions should have the same result:

    x==y andnotx!=y

    x<y andnotx>=y (for total ordering)

    x>y andnotx<=y (for total ordering)

    The last two expressions apply to totally ordered collections (e.g. tosequences, but not to sets or mappings). See also thetotal_ordering() decorator.

  • Thehash() result should be consistent with equality.Objects that are equal should either have the same hash value,or be marked as unhashable.

Python does not enforce these consistency rules. In fact, the not-a-numbervalues are an example for not following these rules.

6.10.2.Membership test operations

The operatorsin andnotin test for membership.xins evaluates toTrue ifx is a member ofs, andFalse otherwise.xnotins returns the negation ofxins. All built-in sequences andset types support this as well as dictionary, for whichin testswhether the dictionary has a given key. For container types such as list, tuple,set, frozenset, dict, or collections.deque, the expressionxiny is equivalenttoany(xiseorx==eforeiny).

For the string and bytes types,xiny isTrue if and only ifx is asubstring ofy. An equivalent test isy.find(x)!=-1. Empty strings arealways considered to be a substring of any other string, so""in"abc" willreturnTrue.

For user-defined classes which define the__contains__() method,xiny returnsTrue ify.__contains__(x) returns a true value, andFalse otherwise.

For user-defined classes which do not define__contains__() but do define__iter__(),xiny isTrue if some valuez, for which theexpressionxiszorx==z is true, is produced while iterating overy.If an exception is raised during the iteration, it is as ifin raisedthat exception.

Lastly, the old-style iteration protocol is tried: if a class defines__getitem__(),xiny isTrue if and only if there is a non-negativeinteger indexi such thatxisy[i]orx==y[i], and no lower integer indexraises theIndexError exception. (If any other exception is raised, it is asifin raised that exception).

The operatornotin is defined to have the inverse truth value ofin.

6.10.3.Identity comparisons

The operatorsis andisnot test for an object’s identity:xisy is true if and only ifx andy are the same object. An Object’s identityis determined using theid() function.xisnoty yields the inversetruth value.[4]

6.11.Boolean operations

or_test  ::=and_test |or_test "or"and_testand_test ::=not_test |and_test "and"not_testnot_test ::=comparison | "not"not_test

In the context of Boolean operations, and also when expressions are used bycontrol flow statements, the following values are interpreted as false:False,None, numeric zero of all types, and empty strings and containers(including strings, tuples, lists, dictionaries, sets and frozensets). Allother values are interpreted as true. User-defined objects can customize theirtruth value by providing a__bool__() method.

The operatornot yieldsTrue if its argument is false,Falseotherwise.

The expressionxandy first evaluatesx; ifx is false, its value isreturned; otherwise,y is evaluated and the resulting value is returned.

The expressionxory first evaluatesx; ifx is true, its value isreturned; otherwise,y is evaluated and the resulting value is returned.

Note that neitherand noror restrict the value and typethey return toFalse andTrue, but rather return the last evaluatedargument. This is sometimes useful, e.g., ifs is a string that should bereplaced by a default value if it is empty, the expressionsor'foo' yieldsthe desired value. Becausenot has to create a new value, itreturns a boolean value regardless of the type of its argument(for example,not'foo' producesFalse rather than''.)

6.12.Assignment expressions

assignment_expression ::= [identifier ":="]expression

An assignment expression (sometimes also called a “named expression” or“walrus”) assigns anexpression to anidentifier, while also returning the value of theexpression.

One common use case is when handling matched regular expressions:

ifmatching:=pattern.search(data):do_something(matching)

Or, when processing a file stream in chunks:

whilechunk:=file.read(9000):process(chunk)

Assignment expressions must be surrounded by parentheses whenused as expression statements and when used as sub-expressions inslicing, conditional, lambda,keyword-argument, and comprehension-if expressions andinassert,with, andassignment statements.In all other places where they can be used, parentheses are not required,including inif andwhile statements.

Added in version 3.8:SeePEP 572 for more details about assignment expressions.

6.13.Conditional expressions

conditional_expression ::=or_test ["if"or_test "else"expression]expression             ::=conditional_expression |lambda_expr

Conditional expressions (sometimes called a “ternary operator”) have the lowestpriority of all Python operations.

The expressionxifCelsey first evaluates the condition,C rather thanx.IfC is true,x is evaluated and its value is returned; otherwise,y isevaluated and its value is returned.

SeePEP 308 for more details about conditional expressions.

6.14.Lambdas

lambda_expr ::= "lambda" [parameter_list] ":"expression

Lambda expressions (sometimes called lambda forms) are used to create anonymousfunctions. The expressionlambdaparameters:expression yields a functionobject. The unnamed object behaves like a function object defined with:

def <lambda>(parameters):    return expression

See sectionFunction definitions for the syntax of parameter lists. Note thatfunctions created with lambda expressions cannot contain statements orannotations.

6.15.Expression lists

starred_expression       ::= ["*"]or_exprflexible_expression      ::=assignment_expression |starred_expressionflexible_expression_list ::=flexible_expression (","flexible_expression)* [","]starred_expression_list  ::=starred_expression (","starred_expression)* [","]expression_list          ::=expression (","expression)* [","]yield_list               ::=expression_list |starred_expression "," [starred_expression_list]

Except when part of a list or set display, an expression listcontaining at least one comma yields a tuple. The length ofthe tuple is the number of expressions in the list. The expressions areevaluated from left to right.

An asterisk* denotesiterable unpacking. Its operand must beaniterable. The iterable is expanded into a sequence of items,which are included in the new tuple, list, or set, at the site ofthe unpacking.

Added in version 3.5:Iterable unpacking in expression lists, originally proposed byPEP 448.

Added in version 3.11:Any item in an expression list may be starred. SeePEP 646.

A trailing comma is required only to create a one-item tuple,such as1,; it is optional in all other cases.A single expression without atrailing comma doesn’t create a tuple, but rather yields the value of thatexpression. (To create an empty tuple, use an empty pair of parentheses:().)

6.16.Evaluation order

Python evaluates expressions from left to right. Notice that while evaluatingan assignment, the right-hand side is evaluated before the left-hand side.

In the following lines, expressions will be evaluated in the arithmetic order oftheir suffixes:

expr1,expr2,expr3,expr4(expr1,expr2,expr3,expr4){expr1:expr2,expr3:expr4}expr1+expr2*(expr3-expr4)expr1(expr2,expr3,*expr4,**expr5)expr3,expr4=expr1,expr2

6.17.Operator precedence

The following table summarizes the operator precedence in Python, from highestprecedence (most binding) to lowest precedence (least binding). Operators inthe 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 forexponentiation and conditional expressions, which group from right to left).

Note that comparisons, membership tests, and identity tests, all have the sameprecedence and have a left-to-right chaining feature as described in theComparisons section.

Operator

Description

(expressions...),

[expressions...],{key:value...},{expressions...}

Binding or parenthesizedexpression,list display,dictionary display,set display

x[index],x[index:index],x(arguments...),x.attribute

Subscription, slicing,call, attribute reference

awaitx

Await expression

**

Exponentiation[5]

+x,-x,~x

Positive, negative, bitwise NOT

*,@,/,//,%

Multiplication, matrixmultiplication, division, floordivision, remainder[6]

+,-

Addition and subtraction

<<,>>

Shifts

&

Bitwise AND

^

Bitwise XOR

|

Bitwise OR

in,notin,is,isnot,<,<=,>,>=,!=,==

Comparisons, including membershiptests and identity tests

notx

Boolean NOT

and

Boolean AND

or

Boolean OR

ifelse

Conditional expression

lambda

Lambda expression

:=

Assignment expression

Footnotes

[1]

Whileabs(x%y)<abs(y) is true mathematically, for floats it may not betrue numerically due to roundoff. For example, and assuming a platform on whicha Python float is an IEEE 754 double-precision number, in order that-1e-100%1e100 have the same sign as1e100, the computed result is-1e-100+1e100, which is numerically exactly equal to1e100. The functionmath.fmod() returns a result whose sign matches the sign of thefirst argument instead, and so returns-1e-100 in this case. Which approachis more appropriate depends on the application.

[2]

If x is very close to an exact integer multiple of y, it’s possible forx//y to be one larger than(x-x%y)//y due to rounding. In suchcases, Python returns the latter result, in order to preserve thatdivmod(x,y)[0]*y+x%y be very close tox.

[3]

The Unicode standard distinguishes betweencode points(e.g. U+0041) andabstract characters (e.g. “LATIN CAPITAL LETTER A”).While most abstract characters in Unicode are only represented using onecode point, there is a number of abstract characters that can in addition berepresented using a sequence of more than one code point. For example, theabstract character “LATIN CAPITAL LETTER C WITH CEDILLA” can be representedas a singleprecomposed character at code position U+00C7, or as asequence of abase character at code position U+0043 (LATIN CAPITALLETTER C), followed by acombining character at code position U+0327(COMBINING CEDILLA).

The comparison operators on strings compare at the level of Unicode codepoints. This may be counter-intuitive to humans. For example,"\u00C7"=="\u0043\u0327" isFalse, even though both stringsrepresent the same abstract character “LATIN CAPITAL LETTER C WITH CEDILLA”.

To compare strings at the level of abstract characters (that is, in a wayintuitive to humans), useunicodedata.normalize().

[4]

Due to automatic garbage-collection, free lists, and the dynamic nature ofdescriptors, you may notice seemingly unusual behaviour in certain uses oftheis operator, like those involving comparisons between instancemethods, or constants. Check their documentation for more info.

[5]

The power operator** binds less tightly than an arithmetic orbitwise unary operator on its right, that is,2**-1 is0.5.

[6]

The% operator is also used for string formatting; the sameprecedence applies.