O'Reilly logo

Python Pocket Reference, 4th Edition by Mark Lutz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Specific Statements

The following sections describe all Python statements. Each section lists the statement’s syntax formats, followed by usage details. For compound statements, each appearance of a suite in a statement format stands for one or more other statements, possibly indented as a block under a header line. A suite must be indented under a header if it contains another compound statement (if, while, etc.); otherwise, it can appear on the same line as the statement header. The following are both valid constructs:

if x < 42:
    print(x)
    while x: x = x − 1

if x < 42: print(x)

The Assignment Statement

target = expression
target1 = target2 = expression
target1, target2 = expression1, expression2
target1 += expression
target1, target2,  ...  = same-length-iterable
(target1, target2, ...) = same-length-iterable
[target1, target2, ...] = same-length-iterable
target1, *target2, ...  = matching–length-iterable

Assignments store references to objects in targets. Expressions yield objects. Targets can be simple names (X), qualified attributes (X.attr), or indexes and slices (X[i], X[i:j]).

The second format assigns an expression object to each target. The third format pairs targets with expressions, left to right. The last three formats assign components of any sequence (or other iterable) to corresponding targets, from left to right. The sequence or iterable on the right must be the same length but can be any type, unless a single starred-name appears in the targets on the left to collect arbitrarily ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required