Operators and Precedence

Table 1 lists Python’s expression operators. Operators in the lower cells of this table have higher precedence (i.e., bind tighter) when used in mixed-operator expressions without parentheses.

Atomic terms and dynamic typing

In Table 1, the replaceable expression items X, Y, Z, i, j, and k may be:

Variable names, replaced with their most recently assigned value

Literal expressions, defined in Specific Built-in Types

Nested expressions, taken from any row in this table, possibly in parentheses

Python variables follow a dynamic typing model — they are not declared, and are created by being assigned; have object references as values, and may reference any type of object; and must be assigned before appearing in expressions, as they have no default value. Case is always significant in variable names (see Name Rules). Objects referenced by variables are automatically created, and automatically reclaimed when no longer in use by Python’s garbage collector, which uses reference counters in CPython.

Also in Table 1, replaceable attr must be the literal (unquoted) name of an attribute; args1 is a formal arguments list as defined in The def Statement; args2 is an input arguments list as defined in The Expression Statement; and a literal … qualifies as an atomic expression in 3.X (only).

The syntax of comprehensions and data structure literals (tuple, list, dictionary, and set) given abstractly in the last three rows of Table 1 is defined in Specific Built-in Types.

Table 1. Python 3.X expression operators and precedence

Operator

Description

yield X

Generator function result (returns send() value)

lambda args1: X

Anonymous function maker (returns X when called)

X if Y else Z

Ternary selection (X is evaluated only if Y is true)

X or Y

Logical OR: Y is evaluated only if X is false

X and Y

Logical AND: Y is evaluated only if X is true

not X

Logical negation

X in Y, X not in Y

Membership: iterables, sets

X is Y, X is not Y

Object identity tests

X < Y, X <= Y, X > Y, X >= Y

Magnitude comparisons, set subset and superset

X == Y, X != Y

Equality operators

X | Y

Bitwise OR, set union

X ^ Y

Bitwise exclusive OR, set symmetric difference

X & Y

Bitwise AND, set intersection

X << Y, X >> Y

Shift X left, right by Y bits

X + Y, X − Y

Addition/concatenation, subtraction/set difference

X * Y, X % Y,

X / Y, X // Y

Multiplication/repetition, remainder/format, division, floor division

-X, +X

Unary negation, identity

˜X

Bitwise NOT complement (inversion)

X ** Y

Power (exponentiation)

X[i]

Indexing (sequence, mapping, others)

X[i:j:k]

Slicing (all three bounds optional)

X(args2)

Call (function, method, class, other callable)

X.attr

Attribute reference

(….)

Tuple, expression, generator expression

[….]

List, list comprehension

{….}

Dictionary, set, dictionary and set comprehension