Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




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.

#!/usr/bin/env python
# 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

print "y=",m,"*x+",b

When we run this program, we get the following output

MacBook-3:Examples slott$ 


y = 1.25 *x+ 0.5

We set variables x1, y1, x2 and y2. Then we computed m and b from those four variables. Then we printed the m and b.

The basic rule is that Python evaluates the entire right-hand side of the = 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
print a,b

We'll return to this in Chapter 13, Tuples , where we'll see additional uses for this feature.

  Published under the terms of the Open Publication License Design by Interspire