Saturday snippet – Tuple assignment

Early this week, I posted a script that did a random shuffle of a collection of objects. That script used tuple assignment to swap elements in a list; here’s a simpler example, with the tuple assignment (line 9) highlighted:

import random
v = [o for o in Application.Selection]

print [o.Name for o in v]

# random shuffle
for i in range( len(v) ):
	j = random.randint( i, len(v)-1 )
	v[i], v[j] = v[j], v[i]

print [o.Name for o in v]

# [u'cube', u'cube1', u'cube2', u'cube3', u'cube4', u'cube5', u'cube6', u'cube7', u'cube8']
# [u'cube5', u'cube4', u'cube7', u'cube2', u'cube1', u'cube3', u'cube', u'cube8', u'cube6']

Looking at that line, you might wonder why you don’t end up assigning the same value to both a[i] and a[j] (eg, how does that line not do a[i] = a[j] and then a[j] = a[i] ?).

In tuple assignment, the right-hand side is considered a tuple of values. So the right-hand side is evaluated first, and then the resulting values are pairwise assigned to the tuple on the left hand side. For example, consider this-rather-more-concrete snippet:

a = 2
b = 8
a,b = b-a,b+a
print a
print b
# 6
# 10

The right-hand side “b-a,b+a” is first evaluated, giving the tuple 6, 10, so you effectively have this:

a,b = 6,10

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s