Multipe Assignment

Harold Nelson

4/5/2018

Multiple Assignment (Continued)

Examples of swapping

x = 1
y = 2
z = 3
t = x,y,z
print(t)
# Swap
## (1, 2, 3)
x,y,z = z,x,y
print(t)
# Note that nothing has changed yet because t still refers to the original objects referenced by x, y and z at the time t was created.
# However, the names x, y and z now refer to differnt objects.
## (1, 2, 3)
t = (x,y,z)
print(t)
# Now the name t refers to a new tuple object.
## (3, 1, 2)

Doodle Make up your own example to illustrate this.

String on the right

The sequence on the right might be a string. The number of variables on the left must match the length of the string.

Example

Pos1, Pos2, Pos3 = 'abc'
print(Pos1)
## a
print(Pos2)
## b
print(Pos3)
## c

The following lines of code will both fail because of mismatches.

print("Failing Examples")
# Pos1, Pos2, Pos3 = 'abcd'
# Pos1, Pos2, Pos3 = 'ab'
## Failing Examples

List on the Right

The right hand side expression might be a list. As always, the number of variables must match the length.

Example

First, Second, Third = ['Tom','Dick','Harry']
print(First)
## Tom
print(Second)
## Dick
print(Third)
## Harry

The list might be created by splitting a string on the fly.

Phone_No = '360-574-9999'
Area_code, Prefix, Number  = Phone_No.split('-')
print(Area_code)
## 360
print(Prefix)
## 574
print(Number)
## 9999
aname = "Jones, Joe"
Last, First = aname.split(', ')
print(First)
## Joe
print(Last)
## Jones

Doodle Time to try an example yourself.