Tuple Statements

The Assignment Sratement. There is a variation on the assignment statement called a multiple-assignment statement that works nicely with tuples. We looked at this in the section called “Multiple Assignment Statement”. Multiple variables are set by decomposing the items in the tuple.

>>>

x,y=(1,2)

>>>

x

1
>>>

y

2
            

An essential ingredient here is that a tuple has a fixed and known number of elements. For example a 2-dimensional geometric point might have a tuple with x and y . A 3-dimensional point might be a tuple with x , y , and z .

This works well because the right side of the assignment statement is fully evaluated before the assignments are performed. This allows things like swapping two variables with x,y=y,x.

The for Statement. The for statement also works directly with sequences like tuples. The range function that we have used creates a list (a kind of sequence covered in the next section). A tuple is also a sequence and can be used in a for statement.

s= 0
for i in ( 1,3,5,7,9, 12,14,16,18, 19,21,23,25,27, 30,32,34,36 ):
    s += i
print "total",s