
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 ::=othernameand no semantics are given, the semantics of this form ofname are the sameas forothername.
When a description of an arithmetic operator below uses the phrase “the numericarguments are converted to a common type,” the arguments are coerced using thecoercion rules listed atCoercion rules. If both arguments are standardnumeric types, the following coercions are applied:
Some additional rules apply for certain operators (e.g., a string left argumentto the ‘%’ operator). Extensions can define their own coercions.
Atoms are the most basic elements of expressions. The simplest atoms areidentifiers or literals. Forms enclosed in reverse quotes or in parentheses,brackets or braces are also categorized syntactically as atoms. The syntax foratoms is:
atom ::=identifier |literal |enclosureenclosure ::=parenth_form |list_display |generator_expression |dict_display |set_display |string_conversion |yield_atom
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.
Private name mangling: When an identifier that textually occurs in a classdefinition begins with two or more underscore characters and does not end in twoor more underscores, it is considered aprivate name of that class.Private names are transformed to a longer form before code is generated forthem. The transformation inserts the class name in front of the name, withleading underscores removed, and a single underscore inserted in front of theclass name. For example, the identifier__spam occurring in a class namedHam will be transformed to_Ham__spam. This transformation isindependent of the syntactical context in which the identifier is used. If thetransformed name is extremely long (longer than 255 characters), implementationdefined truncation may happen. If the class name consists only of underscores,no transformation is done.
Python supports string literals and various numeric literals:
literal ::=stringliteral |integer |longinteger |floatnumber |imagnumber
Evaluation of a literal yields an object of the given type (string, integer,long integer, floating point number, complex number) with the given value. Thevalue may 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.
A parenthesized form is an optional expression list enclosed in parentheses:
parenth_form ::= "(" [expression_list] ")"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 rules 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 operator. The exception is the empty tuple, for which parenthesesarerequired — allowing unparenthesized “nothing” in expressions would causeambiguities and allow common typos to pass uncaught.
A list display is a possibly empty series of expressions enclosed in squarebrackets:
list_display ::= "[" [expression_list |list_comprehension] "]"list_comprehension ::=expressionlist_forlist_for ::= "for"target_list "in"old_expression_list [list_iter]old_expression_list ::=old_expression [(","old_expression)+ [","]]old_expression ::=or_test |old_lambda_formlist_iter ::=list_for |list_iflist_if ::= "if"old_expression [list_iter]
A list display yields a new list object. Its contents are specified byproviding either a list of expressions or a list comprehension. When acomma-separated list of expressions is supplied, its elements are evaluated fromleft to right and placed into the list object in that order. When a listcomprehension is supplied, it consists of a single expression followed by atleast onefor clause and zero or morefor orifclauses. In this case, the elements of the new list are those that would beproduced by considering each of thefor orif clauses ablock, nesting from left to right, and evaluating the expression to produce alist element each time the innermost block is reached[1].
For constructing a set or a dictionary Python provides special syntaxcalled “displays”, each of them in two flavors:
Common syntax elements for comprehensions are:
comprehension ::=expressioncomp_forcomp_for ::= "for"target_list "in"or_test [comp_iter]comp_iter ::=comp_for |comp_ifcomp_if ::= "if"expression_nocond [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.
Note that the comprehension is executed in a separate scope, so names assignedto in the target list don’t “leak” in the enclosing scope.
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 generator object (in the same fashion asnormal generators). However, the leftmostfor clause is immediatelyevaluated, so that an error produced by it can be seen before any other possibleerror in the code that handles the generator expression. Subsequentfor clauses cannot be evaluated immediately since they may depend onthe previousfor loop. For example:(x*yforxinrange(10)foryinbar(x)).
The parentheses can be omitted on calls with only one argument. See sectionCalls for the detail.
A dictionary display is a possibly empty series of key/datum pairs enclosed incurly braces:
dict_display ::= "{" [key_datum_list |dict_comprehension] "}"key_datum_list ::=key_datum (","key_datum)* [","]key_datum ::=expression ":"expressiondict_comprehension ::=expression ":"expressioncomp_forA dictionary display yields a new dictionary object.
If a comma-separated sequence of key/datum pairs 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 datum. This meansthat you can specify the same key multiple times in the key/datum list, and thefinal dictionary’s value for that key will be the last one given.
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 lastdatum (textually rightmost in the display) stored for a given key valueprevails.
A set display is denoted by curly braces and distinguishable from dictionarydisplays by the lack of colons separating keys and values:
set_display ::= "{" (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.
A string conversion is an expression list enclosed in reverse (a.k.a. backward)quotes:
string_conversion ::= "`"expression_list "`"
A string conversion evaluates the contained expression list and converts theresulting object into a string according to rules specific to its type.
If the object is a string, a number,None, or a tuple, list or dictionarycontaining only objects whose type is one of these, the resulting string is avalid Python expression which can be passed to the built-in functioneval() to yield an expression with the same value (or an approximation, iffloating point numbers are involved).
(In particular, converting a string adds quotes around it and converts “funny”characters to escape sequences that are safe to print.)
Recursive objects (for example, lists or dictionaries that contain a referenceto themselves, directly or indirectly) use... to indicate a recursivereference, and the result cannot be passed toeval() to get an equal value(SyntaxError will be raised instead).
The built-in functionrepr() performs exactly the same conversion in itsargument as enclosing it in parentheses and reverse quotes does. The built-infunctionstr() performs a similar but more user-friendly conversion.
yield_atom ::= "("yield_expression ")"yield_expression ::= "yield" [expression_list]New in version 2.5.
Theyield expression is only used when defining a generator function,and can only be used in the body of a function definition. Using ayield expression in a function definition is sufficient to cause thatdefinition to create a generator function instead of a normal function.
When a generator function is called, it returns an iterator known as agenerator. That generator then controls the execution of a generator function.The execution starts when one of the generator’s methods is called. At thattime, the execution proceeds to the firstyield expression, where itis suspended again, returning the value ofexpression_list togenerator’s caller. By suspended we mean that all local state is retained,including the current bindings of local variables, the instruction pointer, andthe internal evaluation stack. When the execution is resumed by calling one ofthe generator’s methods, the function can proceed exactly as if theyield expression was just another external call. The value of theyield expression after resuming depends on the method which resumedthe execution.
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 should the execution continue after it yields; the control is alwaystransferred to the generator’s caller.
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.
Starts the execution of a generator function or resumes it at the last executedyield expression. When a generator function is resumed with anext() method, the currentyield expression always evaluates toNone. The execution then continues to the nextyieldexpression, where the generator is suspended again, and the value of theexpression_list is returned tonext()‘s caller. If the generatorexits without yielding another value, aStopIteration exception israised.
Resumes the execution and “sends” a value into the generator function. Thevalue argument becomes the result of the currentyieldexpression. Thesend() method returns the next value yielded by thegenerator, or raisesStopIteration if the generator exits withoutyielding another value. Whensend() is called to start the generator, itmust be called withNone as the argument, because there is noyield expression that could receive the value.
Raises an exception of typetype at the point where 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.
Raises aGeneratorExit at the point where the generator function waspaused. If the generator function then raisesStopIteration (by exitingnormally, or due to already being closed) orGeneratorExit (by notcatching the exception), close returns to its caller. If the generator yields avalue, aRuntimeError is raised. If the generator raises any otherexception, it is propagated to the caller.close() does nothing if thegenerator has already exited due to an exception or normal exit.
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)...exceptException,e:...value=e...finally:...print"Don't forget to clean up when 'close()' is called."...>>>generator=echo(1)>>>printgenerator.next()Execution starts when 'next()' is called for the first time.1>>>printgenerator.next()None>>>printgenerator.send(2)2>>>generator.throw(TypeError,"spam")TypeError('spam',)>>>generator.close()Don't forget to clean up when 'close()' is called.
See also
Primaries represent the most tightly bound operations of the language. Theirsyntax is:
primary ::=atom |attributeref |subscription |slicing |call
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, e.g., a module, list, or an instance. This object is then asked toproduce the attribute whose name is the identifier. If this attribute is notavailable, the exceptionAttributeError is raised. Otherwise, the typeand value of the object produced is determined by the object. Multipleevaluations of the same attribute reference may yield different objects.
A subscription selects an item of a sequence (string, tuple or list) or mapping(dictionary) object:
subscription ::=primary "["expression_list "]"
The primary must evaluate to an object of a sequence or mapping type.
If the primary is a mapping, the expression list must evaluate to an objectwhose value is one of the keys of the mapping, and the subscription selects thevalue in the mapping that corresponds to that key. (The expression list is atuple except if it has exactly one item.)
If the primary is a sequence, the expression (list) must evaluate to a plaininteger. If this value is negative, the length of the sequence is added to it(so that, e.g.,x[-1] selects the last item ofx.) The resulting valuemust be a nonnegative integer less than the number of items in the sequence, andthe subscription selects the item whose index is that value (counting fromzero).
A string’s items are characters. A character is not a separate data type but astring of exactly one character.
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 ::=simple_slicing |extended_slicingsimple_slicing ::=primary "["short_slice "]"extended_slicing ::=primary "["slice_list "]"slice_list ::=slice_item (","slice_item)* [","]slice_item ::=expression |proper_slice |ellipsisproper_slice ::=short_slice |long_sliceshort_slice ::= [lower_bound] ":" [upper_bound]long_slice ::=short_slice ":" [stride]lower_bound ::=expressionupper_bound ::=expressionstride ::=expressionellipsis ::= "..."
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 nor ellipses). Similarly, when the slicelist has exactly one short slice and no trailing comma, the interpretation as asimple slicing takes priority over that as an extended slicing.
The semantics for a simple slicing are as follows. The primary must evaluate toa sequence object. The lower and upper bound expressions, if present, mustevaluate to plain integers; defaults are zero and thesys.maxint,respectively. If either bound is negative, the sequence’s length is added toit. The slicing now selects all items with indexk such thati<=k<jwherei andj are the specified lower and upper bounds. This may be anempty sequence. It is not an error ifi orj lie outside the range of validindexes (such items don’t exist so they aren’t selected).
The semantics for an extended slicing are as follows. The primary must evaluateto a mapping object, and it is indexed with a key that is constructed from theslice list, as follows. If the slice list contains at least one comma, the keyis a tuple containing the conversion of the slice items; otherwise, theconversion of the lone slice item is the key. The conversion of a slice itemthat is an expression is that expression. The conversion of an ellipsis sliceitem is the built-inEllipsis object. The conversion of a proper slice is aslice object (see sectionThe standard type hierarchy) whosestart,stop andstep attributes are the values of the expressions given as lower bound,upper bound and stride, respectively, substitutingNone for missingexpressions.
A call calls a callable object (e.g., a function) with a possibly empty seriesof arguments:
call ::=primary "(" [argument_list [","] |expressiongenexpr_for] ")"argument_list ::=positional_arguments [","keyword_arguments] ["," "*"expression] [","keyword_arguments] ["," "**"expression] |keyword_arguments ["," "*"expression] ["," "**"expression] | "*"expression ["," "*"expression] ["," "**"expression] | "**"expressionpositional_arguments ::=expression (","expression)*keyword_arguments ::=keyword_item (","keyword_item)*keyword_item ::=identifier "="expression
A trailing comma may be present after the positional and keyword arguments butdoes 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 certain class instances themselves are callable; extensions maydefine additional callable object types). All argument expressions areevaluated before the call is attempted. Please refer to sectionFunction definitionsfor the syntax of formal parameter 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, the value ofthe argument 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 an iterable. Elements from this iterable are treated as if theywere additional positional arguments; if there are positional argumentsx1, ...,xN, andexpression evaluates to a sequencey1, ...,yM, thisis equivalent to a call with M+N positional argumentsx1, ...,xN,y1,...,yM.
A consequence of this is that although the*expression syntax may appearafter some keyword arguments, it is processedbefore the keyword arguments(and the**expression argument, if any – see below). So:
>>>deff(a,b):...printa,b...>>>f(b=1,*(2,))2 1>>>f(a=1,*(2,))Traceback (most recent call last): File"<stdin>", line1, in?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 arise.
If the syntax**expression appears in the function call,expression mustevaluate to a mapping, the contents of which are treated as additional keywordarguments. In the case of a keyword appearing in bothexpression and as anexplicit keyword argument, aTypeError exception is raised.
Formal parameters using the syntax*identifier or**identifier cannot beused as positional argument slots or as keyword argument names. Formalparameters using the syntax(sublist) cannot be used as keyword argumentnames; the outermost sublist corresponds to a single unnamed argument slot, andthe argument value is assigned to the sublist using the usual tuple assignmentrules after all other parameter processing is done.
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—
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.
The result is up to the interpreter; seeBuilt-in Functions for thedescriptions of built-in functions and methods.
A new instance of that class is returned.
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.
The class must define a__call__() method; the effect is then the same asif that method was called.
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 ::=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. The result type is that of the arguments after coercion.
With mixed operand types, the coercion rules for binary arithmetic operatorsapply. For int and long int operands, the result has the same type as theoperands (after coercion) unless the second argument is negative; in that case,all arguments are converted to float and a float result is delivered. Forexample,10**2 returns100, but10**-2 returns0.01. (This lastfeature was added in Python 2.2. In Python 2.1 and before, if both argumentswere of integer types and the second argument was negative, an exception wasraised).
Raising0.0 to a negative power results in aZeroDivisionError.Raising a negative number to a fractional power results in aValueError.
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.
The unary+ (plus) operator yields its numeric argument unchanged.
The unary~ (invert) operator yields the bitwise inversion of its plain orlong integer argument. The bitwise inversion ofx is defined as-(x+1). It only applies to integral numbers.
In all three cases, if the argument does not have the proper type, aTypeError exception is raised.
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 "//"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 (plainor long) and the other must be a sequence. In the former case, the numbers areconverted to a common type and then multiplied together. In the latter case,sequence repetition is performed; a negative repetition factor yields an emptysequence.
The/ (division) and// (floor division) operators yield the quotient oftheir arguments. The numeric arguments are first converted to a common type.Plain or long integer division yields an integer of the same type; the result isthat of mathematical division with the ‘floor’ function applied to the result.Division by zero raises theZeroDivisionError exception.
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[2].
The integer division and modulo operators are connected by the followingidentity:x==(x/y)*y+(x%y). Integer division and modulo are alsoconnected with the built-in functiondivmod():divmod(x,y)==(x/y,x%y). These identities don’t hold for floating point numbers; there similaridentities hold approximately wherex/y is replaced byfloor(x/y) orfloor(x/y)-1[3].
In addition to performing the modulo operation on numbers, the% operator isalso overloaded by string and unicode objects to perform string formatting (alsoknown as interpolation). The syntax for string formatting is described in thePython Library Reference, sectionString Formatting Operations.
Deprecated since version 2.3:The floor division operator, the modulo operator, and thedivmod()function are no longer 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 sequences of the same type. In the formercase, the numbers are converted to a common type and then added together. Inthe latter case, the sequences are concatenated.
The- (subtraction) operator yields the difference of its arguments. Thenumeric arguments are first converted to a common type.
The shifting operations have lower priority than the arithmetic operations:
shift_expr ::=a_expr |shift_expr ( "<<" | ">>" )a_expr
These operators accept plain or long integers as arguments. The arguments areconverted to a common type. They shift the first argument to the left or rightby the number of bits given by the second argument.
A right shift byn bits is defined as division bypow(2,n). A left shiftbyn bits is defined as multiplication withpow(2,n). Negative shiftcounts raise aValueError exception.
Note
In the current implementation, the right-hand operand is requiredto be at mostsys.maxsize. If the right-hand operand is larger thansys.maxsize anOverflowError exception is raised.
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 be plainor long integers. The arguments are converted to a common type.
The^ operator yields the bitwise XOR (exclusive OR) of its arguments, whichmust be plain or long integers. The arguments are converted to a common type.
The| operator yields the bitwise (inclusive) OR of its arguments, whichmust be plain or long integers. The arguments are converted to a common type.
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.
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).
The forms<> and!= are equivalent; for consistency with C,!= ispreferred; where!= is mentioned below<> is also accepted. The<>spelling is considered obsolescent.
The operators<,>,==,>=,<=, and!= compare thevalues of two objects. The objects need not have the same type. If both arenumbers, they are converted to a common type. Otherwise, objects of differenttypesalways compare unequal, and are ordered consistently but arbitrarily.You can control comparison behavior of objects of non-built-in types by defininga__cmp__ method or rich comparison methods like__gt__, described insectionSpecial method names.
(This unusual definition of comparison was used to simplify the definition ofoperations like sorting and thein andnotin operators.In the future, the comparison rules for objects of different types are likely tochange.)
Comparison of objects of the same type depends on the type:
Numbers are compared arithmetically.
Strings are compared lexicographically using the numeric equivalents (theresult of the built-in functionord()) of their characters. Unicode and8-bit strings are fully interoperable in this behavior.[4]
Tuples and lists are compared lexicographically using comparison ofcorresponding elements. This means that to compare equal, each element mustcompare equal and the two sequences must be of the same type and have the samelength.
If not equal, the sequences are ordered the same as their first differingelements. For example,cmp([1,2,x],[1,2,y]) returns the same ascmp(x,y). If the corresponding element does not exist, the shorter sequenceis ordered first (for example,[1,2]<[1,2,3]).
Mappings (dictionaries) compare equal if and only if their sorted (key, value)lists compare equal.[5] Outcomes other than equality are resolvedconsistently, but are not otherwise defined.[6]
Most other objects of built-in types compare unequal unless they are the sameobject; the choice whether one object is considered smaller or larger thananother one is made arbitrarily but consistently within one execution of aprogram.
The operatorsin andnotin test for collectionmembership.xins evaluates to true ifx is a member of the collections, and false otherwise.xnotins returns the negation ofxins.The collection membership test has traditionally been bound to sequences; anobject is a member of a collection if the collection is a sequence and containsan element equal to that object. However, it make sense for many other objecttypes to support membership tests without being a sequence. In particular,dictionaries (for keys) and sets support membership testing.
For the list and tuple types,xiny is true if and only if there exists anindexi such thatx==y[i] is true.
For the Unicode and string types,xiny is true if and only ifx is asubstring ofy. An equivalent test isy.find(x)!=-1. Note,x andyneed not be the same type; consequently,u'ab'in'abc' will returnTrue. Empty strings are always considered to be a substring of any otherstring, so""in"abc" will returnTrue.
Changed in version 2.3:Previously,x was required to be a string of length1.
For user-defined classes which define the__contains__() method,xiny is true if and only ify.__contains__(x) is true.
For user-defined classes which do not define__contains__() but do define__iter__(),xiny is true if some valuez withx==z isproduced while iterating overy. If an exception is raised during theiteration, it is as ifin raised that exception.
Lastly, the old-style iteration protocol is tried: if a class defines__getitem__(),xiny is true if and only if there is a non-negativeinteger indexi such thatx==y[i], and all lower integer indices do notraiseIndexError exception. (If any other exception is raised, it is asifin raised that exception).
The operatornotin is defined to have the inverse true value ofin.
The operatorsis andisnot test for object identity:xisy is true if and only ifx andy are the same object.xisnotyyields the inverse truth value.[7]
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. (See the__nonzero__()special method for a way to change this.)
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 invent a value anyway, it doesnot bother to return a value of the same type as its argument, so e.g.,not'foo' yieldsFalse, not''.)
New in version 2.5.
conditional_expression ::=or_test ["if"or_test "else"expression]expression ::=conditional_expression |lambda_form
Conditional expressions (sometimes called a “ternary operator”) have the lowestpriority of all Python operations.
The expressionxifCelsey first evaluates the condition,C (notx);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.
lambda_form ::= "lambda" [parameter_list]:expressionold_lambda_form ::= "lambda" [parameter_list]:old_expression
Lambda forms (lambda expressions) have the same syntactic position asexpressions. They are a shorthand to create anonymous functions; the expressionlambdaarguments:expression yields a function object. The unnamed objectbehaves like a function object defined with
defname(arguments):returnexpression
See sectionFunction definitions for the syntax of parameter lists. Note thatfunctions created with lambda forms cannot contain statements.
expression_list ::=expression ( ","expression )* [","]
An expression list containing 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.
The trailing comma is required only to create a single tuple (a.k.a. asingleton); 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:().)
Python evaluates expressions from left to right. Notice that while evaluating anassignment, 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
The following table summarizes the operator precedences in Python, from lowestprecedence (least binding) to highest precedence (most 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 forcomparisons, including tests, which all have the same precedence and chain fromleft to right — see sectionComparisons — and exponentiation, whichgroups from right to left).
| Operator | Description |
|---|---|
| lambda | Lambda expression |
| if –else | Conditional expression |
| or | Boolean OR |
| and | Boolean AND |
| notx | Boolean NOT |
| in,notin,is,isnot,<,<=,>,>=,<>,!=,== | Comparisons, including membershiptests and identity tests, |
| | | Bitwise OR |
| ^ | Bitwise XOR |
| & | Bitwise AND |
| <<,>> | Shifts |
| +,- | Addition and subtraction |
| *,/,//,% | Multiplication, division, remainder[8] |
| +x,-x,~x | Positive, negative, bitwise NOT |
| ** | Exponentiation[9] |
| x[index],x[index:index],x(arguments...),x.attribute | Subscription, slicing,call, attribute reference |
| (expressions...),[expressions...],{key:datum...},`expressions...` | Binding or tuple display,list display,dictionary display,string conversion |
Footnotes
| [1] | In Python 2.3 and later releases, a list comprehension “leaks” the controlvariables of eachfor it contains into the containing scope. However, thisbehavior is deprecated, and relying on it will not work in Python 3. |
| [2] | 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. |
| [3] | If x is very close to an exact integer multiple of y, it’s possible forfloor(x/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. |
| [4] | While comparisons between unicode strings make sense at the bytelevel, they may be counter-intuitive to users. For example, thestringsu"\u00C7" andu"\u0043\u0327" compare differently,even though they both represent the same unicode character (LATINCAPITAL LETTER C WITH CEDILLA). To compare strings in a humanrecognizable way, compare usingunicodedata.normalize(). |
| [5] | The implementation computes this efficiently, without constructing lists orsorting. |
| [6] | Earlier versions of Python used lexicographic comparison of the sorted (key,value) lists, but this was very expensive for the common case of comparing forequality. An even earlier version of Python compared dictionaries by identityonly, but this caused surprises because people expected to be able to test adictionary for emptiness by comparing it to{}. |
| [7] | 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. |
| [8] | The% operator is also used for string formatting; the sameprecedence applies. |
| [9] | The power operator** binds less tightly than an arithmetic orbitwise unary operator on its right, that is,2**-1 is0.5. |
Enter search terms or a module, class or function name.