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. Python 3.0 expression operators and precedence

Operator

Description

yield X

Generator function send() protocol

lambda args: expr

Anonymous function maker

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 != YEquality 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 bounds optional)

X(...)

Call (function, method, class, other callable)

X.attr

Attribute reference

(...)

Tuple, expression, generator expression

[...]

List, list comprehension

{...}

Dictionary, set, dictionary and set comprehension

Operator Usage Notes

  • In ...

Get Python Pocket Reference, 4th 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.