Multiple Assignment Statement
The basic assignment statement does more than assign the result of a
single expression to a single variable. The assignment satement also copes
nicely with assigning multiple variables at one time. The left and right
side must have the same number of elements. For example, the following
script has several examples of multiple assignment.
Example 6.7. line.py
# Compute line between two points.
x1,y1 = 2,3 # point one
x2,y2 = 6,8 # point two
m,b = float(y1-y2)/(x1-x2), y1-float(y1-y2)/(x1-x2)*x1
When we run this program, we get the following output
y = 1.25 *x+ 0.5
We set variables
y2. Then we computed
b from those four variables.
Then we printed the
The basic rule is that Python evaluates the entire right-hand side
statement. Then it matches values with
destinations on the left-hand side. If the lists are different lengths, an
exception is raised and the program stops.
Because of the complete evaluation of the right-hand side, the
following construct works nicely to swap to variables. This is often quite
a bit more complicated in other languages.
a,b = 1,4
b,a = a,b
We'll return to this in Chapter 13, Tuples
we'll see additional uses for this feature.