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 |
---|---|
| Generator function
|
| Anonymous function maker |
| Ternary selection
( |
| Logical |
| Logical |
| Logical negation |
| Membership: iterables, sets |
| Object identity tests |
| Magnitude comparisons, set subset and superset |
X == Y , X != Y | Equality operators |
| Bitwise |
| Bitwise exclusive
|
| Bitwise |
| Shift |
| Addition/concatenation, subtraction/set difference |
| Multiplication/repetition, remainder/format, division, floor division |
| Unary negation, identity |
| Bitwise NOT complement (inversion) |
| Power (exponentiation) |
| Indexing (sequence, mapping, others) |
| Slicing (all bounds optional) |
| Call (function, method, class, other callable) |
| Attribute reference |
| Tuple, expression, generator expression |
| List, list comprehension |
| Dictionary, set, dictionary and set comprehension |
In Python 2.6, value inequality can be written as
either X != Y
or X <> Y
. In Python 3.0, the latter
of these options is removed because it is redundant.
In Python 2.6, a backquotes expression `X`
works the same as repr(X)
, and converts objects to display
strings. In Python 3.0, use the more readable str()
and repr()
built-in functions
instead.
In both Python 3.0 and 2.6, the X
// Y
floor division expression
always truncates fractional remainders, and returns an integer result for
integers.
The X / Y
expression
performs true division in 3.0 (always
retaining remainders in a floating-point result), and
classic division in 2.6 (truncating
remainders for integers).
The syntax [...]
is used
for both list literals and list comprehension expressions. The
latter of these performs an implied loop and collects expression
results in a new list.
The syntax (...)
is used
for tuples and expressions, as well as generator expressions—a
form of list comprehension that produces results on demand,
instead of building a result list. Parenthesis may sometimes be
omitted in all three constructs.
The syntax {...}
is used
for dictionary literals. In Python 3.0, it is also used for set
literals, and both dictionary and set comprehensions; use set()
and looping statements in
2.6.
The yield
and ternary
if
/else
selection expressions are available
in Python 2.5 and later. The former returns send()
arguments in generators; the
latter is a shorthand for a multiline if
statement. yield
requires parentheses if not alone
on the right side of an assignment statement.
Comparison operators may be chained: X < Y < Z
produces the same result
as X < Y and Y < Z
, but
Y
is evaluated only once in the
chained form.
The slice expression X[I:J:K]
is equivalent to indexing with
a slice object: X[slice(I, J,
K)]
.
In Python 2.6, magnitude comparisons of mixed types are allowed—converting numbers to a common type, and ordering other mixed types according to the type name. In Python 3.0, nonnumeric mixed-type magnitude comparisons are not allowed, and raise exceptions; this includes sorts by proxy.
Magnitude comparisons for dictionaries are also no longer
supported in Python 3.0 (though equality tests are); comparing
sorted(dict.items())
is one
possible replacement in 3.0.
Call expressions allow for positional and keyword arguments, and arbitrarily large numbers of both; see The Expression Statement and The def Statement for call syntax.
Python 3.0 allows ellipsis (literally, ...
) to be used as an atomic expression
anywhere in source code. This may be used as an alternative to
pass
or None
in some contexts (e.g., stubbed-out
function bodies, type-independent variable initialization).
All built-in types support the comparisons and Boolean operations listed in Table 1-2.
Boolean true
means any nonzero number or any nonempty
collection object (list, dictionary, etc.). The built-in names
True
and False
are pre-assigned to true and false
values and behave like integers 1 and 0 with custom display formats.
The special object None
is
false.
Comparisons return True
or
False
and are applied recursively
in compound objects as needed to determine a result.
Boolean and
and or
operators stop (short-circuit) as soon as
a result is known and return one of the two operand objects (on left
or right).
Table 1-2. Comparisons and Boolean operations
Operator | Description |
---|---|
| Strictly less than[a] |
| Less than or equal to |
| Strictly greater than |
| Greater than or equal to |
| Equal to (same value) |
| Not equal to (same as
|
| Same object |
| Negated object identity |
| Chained comparisons |
| If |
| If |
| If |
[a] To implement comparison expressions, see both the
rich comparison (e.g., [b] |
Tables 1-3 through 1-6 define operations common to types in the three major type categories (sequence, mapping, and number), as well as operations available for mutable (changeable) types in Python. Most types also export additional type-specific operations (e.g., methods), as described in the section Specific Built-in Types.
Table 1-3. Sequence operations (strings, lists, tuples, bytes, bytearray)
Operation | Description | Class method |
---|---|---|
| Membership tests |
|
| Concatenation |
|
| Repetition |
|
| Index by offset |
|
| Slicing: items in S
from offset |
|
| Length |
|
| Minimum, maximum item |
|
| Iteration protocol |
|
| Iteration (all contexts) |
|
[a] See also iterators, generators, and the [b] In Python 2.6, you may also define |
Table 1-5. Mapping operations (dictionaries)
Operation | Description | Class method |
---|---|---|
|
| |
| Key assignment: change
or create entry for key |
|
| Delete item by key |
|
| Length (number of keys) |
|
| Key membership test[a] | Same as in Table 1-3 |
| Converse of | Same as in Table 1-3 |
| Iterator object for keys | Same as in Table 1-3 |
| Iterate through keys in
| Same as in Table 1-3 |
[a] In Python 2.X, key membership may also be coded as
|
Table 1-6. Numeric operations (all number types)
Operation | Description | Class method |
---|---|---|
|
| |
| Multiply, divide, floor divide, remainder |
|
| Negative, identity |
|
| Bitwise |
|
| Bitwise left-shift, right-shift (integers) |
|
| Bitwise invert (integers) |
|
|
|
|
| Absolute value |
|
| Convert to integer[a] |
|
| Convert to float |
|
| Make a complex value |
|
| Tuple: |
|
| Raise to a power |
|
[a] In Python 2.6, the |
Slice boundaries default to 0 and sequence length.
S[1:3]
fetches from
offsets 1 up to, but not including, 3.
S[1:]
fetches from
offsets 1 through the end (length-1).
S[:−1]
fetches from
offsets 0 up to, but not including, the last item.
S[:]
makes a top-level
(shallow) copy of sequence object S
.
Slice assignment is similar to deleting and then inserting.
If present, the third item k
is a stride: added to the offset of
each item extracted.
S[::2]
is every other
item in sequence S
.
S[::−1]
is sequence
S
reversed.
S[4:1:−1]
fetches from
offsets 4 up to, but not including, 1, reversed.