A statement like w = x = y = z
is called a chained assignment in which the value of z
is assigned to multiple variables w, x,
and y
. Chained assignments are often used to initialize multiple variables, as in
a = b = c = d = f = 0
Not all programming languages support chained assignment.
In some programming languages (C for example), chained assignments are supported because assignments return values. In C++ they are also available for values of class types by making appropriate return type for the assignment operator. This is however strongly discouraged because it also allows values of class types to be assigned to temporary objects, which results in a statement with no effect (assignment to temporary objects is detected as error only for non-class types).
In Python, assignment statements are not expressions and thus do not return a value. Instead, chained assignments are a series of statements with multiple targets for a single expression. The assignments are executed left-to-right so that i = arr = f
evaluates the expression f
, then assigns the result to the leftmost target, i
, and then assigns the same result to the next target, arr
, using the new value of i
.
Read more about this topic: Assignment (computer Science)
Famous quotes containing the word chained:
“They dragged you from homeland,
They chained you in coffles,
They huddled you spoon-fashion in filthy hatches,
They sold you to give a few gentlemen ease.”
—Sterling Allen Brown (b. 1901)