Built-in Types and Operators

Operators and Precedence

Table 1-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.

Table 1-1. Expression operators and precedence

Operators

Description

lambda args: expr

Anonymous function maker

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 < Y, X <= Y, X > Y, 
X >= Y, X == Y, X <> Y, 
X != Y, X is Y, X is not Y, 
X in S, X not in S

Comparison operators,[a] equality operators, inequality operators, object identity tests, sequence membership

X | Y

Bitwise OR

X ^ Y

Bitwise exclusive OR

X & Y

Bitwise AND

X << Y, X >> Y

Shift X left, right by Y bits

X + Y, X—Y

Addition/concatenation, subtraction

X * Y, X % Y,
X / Y, X // Y

Multiply/repetition, remainder/format, division, floor division[b]

-X, +X, ~X, X**Y

Unary negation, identity, bitwise complement, power

X[i], X[i:j], 
X.attr, X(...)

Indexing, slicing, attribute references, function calls

(...), [...], {...}, `...`

Tuple, list,[c] dictionary, conversion to string[d]

[a] Comparison operators may be chained: x < y < z is similar to x < y and y < z, except that y is evaluated only once in the first format.

[b] Floor division (X // Y), new in 2.2, always truncates fractional remainders. Classic division (X / Y) truncates integer division results in 2.2 but will ...

Get Python Pocket Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.