Expressions and Operators
An expression is a phrase of code that the Python interpreter can evaluate to produce a value. The simplest expressions are literals and identifiers. You build other expressions by joining subexpressions with the operators and/or delimiters in Table 4-2. This table lists the operators in decreasing order of precedence, so operators with higher precedence are listed before those with lower precedence. Operators listed together have the same precedence. The A column lists the associativity of the operator, which can be L (left-to-right), R (right-to-left), or NA (non-associative).
In Table 4-2, expr,
key, f,
index, x, and
y indicate any expression, while
attr and arg
indicate identifiers. The notation ,... indicates
that commas join zero or more repetitions, except for string
conversion, where one or more repetitions are allowed. A trailing
comma is also allowed and innocuous in all such cases, except with
string conversion, where it’s
forbidden.
Table 4-2. Operator precedence in expressions
|
Operator |
Description |
A |
|---|---|---|
`
|
String conversion |
NA |
{
|
Dictionary creation |
NA |
[
|
List creation |
NA |
(
|
Tuple creation or simple parentheses |
NA |
|
Function call |
L |
|
Slicing |
L |
|
Indexing |
L |
|
Attribute reference |
L |
|
Exponentiation
( |
R |
~
|
Bitwise NOT |
NA |
|
|
Unary plus and minus |
NA |
|
|
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access