Swap two objects in python

Swapping the contents of two objects in python is so simple you wouldn’t believe.

// yes, it's as simple as reassigning them.
a,b = b,a

So how does this work?
1. First, the right-hand side b,a is evaluated: this means a tuple of two elements is created in memory. The two elements are the objects designated by the identifiers b and a, that existed before the instruction was encountered.

After the creation of this tuple, no assignments of this tuple object have been made yet.

2. Then, the left-hand side is evaluated: this means the tuple is assigned to the left-hand side. Since the left-hand side is composed of two identifiers, the tuple is unpacked in order to assign the first identifier a to the first element of the tuple (the object that was formerly b before the swap) and the second identifier b is assigned to the second element of the tuple (the object that was formerly a before the swap).
This mechanism has effectively swapped the objects assigned to the identifiers a and b.

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: