Marquette University, view of Wisconsin Avenue  

Module 22

Tuples, Sets, and Frozen Sets

Python has quite a large set of native data structures. The most important one remaining is the tuple. Sets are nifty because they only distinguish between members and non-members, whereas in a list, an element can appear multiple times. A set is mutable, but a frozen-set is like an immutable set, that consequentially can be used as the key to a dictionary.

Tuples

One can think of tuples as an immutable list, and in fact, you can treat tuples as lists using indices. A tuple is created using round parentheses.

Tuple Assignment

Tuple assignment is a neat feature of Python, where the left and the right side of the assignment are tuples (of the same length). Python first evaluates the right side, and only then assigns tuple component for tuple component to the left side. If you want to swap the values of two variables a and b we just use

a, b = b, a

This is not the same as the following, WRONG code

 
a = b
b = a   #WILL NOT WORK

After the first statement, the value of a is that of b, but its original value has been overwritten and is no longer there. Without tuple assignment, we need to use a temporary variable that saves the old value of a :

temp = a
a = b
b = temp

Unpacking

We had already need for a function to obtain more than one value. Now we can do so, because we can return a tuple. Then we use tuple assignment in order to assign the return value to a tuple of parameters. For example, if we define a function

def func(a,b,c):
   ... some stuff here ...
   return x, y

of three parameters that returns two return values, we can get the return values by

my_x, my_y = func(a,b,c)