Built-in Types and Operators

Operators and Precedence

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

Table 1-1. Operators and Precedence



X or Y, 
lambda args: expr

Logical ‘or’ (Y is only evaluated if X is false), anonymous function

X and Y

Logical ‘and’ (Y is only evaluated 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, equality operators, identity tests, sequence membership

X | Y

Bitwise ‘or’

X ^ Y

Bitwise ‘exclusive or’

X & Y

Bitwise ‘and’

X << Y, X >> Y

Shift X left or right by Y bits

X + Y, X — Y

Addition/concatenation, subtraction

X * Y, X / Y, X % Y

Multiply/repetition, divide, remainder/format

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

Unary negation, identity, bitwise complement, power

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

Indexing, slicing, qualification, function calls

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

Tuple, list, dictionary, conversion to string

Operations by Category

All types support comparisons and boolean operations.

  • True means any non-zero number, or any non-empty collection object (list, dictionary, etc.). The special object None is false.

  • Comparisons return 1 or 0 and are applied recursively in compound objects as needed to determine a result.

  • Boolean and and or operators stop as soon as a result is known (short-circuit) and return an operand object.

Table 1-2. Comparisons ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.