Tuples

Tuples are another object type in Python. Tuples are like lists, except that tuples are immutable. Here is how a tuple is defined:

In [1]:
t = (1, 2, 3, 4)

You can access elements of tuples just like you access elements of lists:

In [2]:
t[1]
Out[2]:
2
In [3]:
t[1:]
Out[3]:
(2, 3, 4)

Tuples can contain objects that are not tuples inside them:

In [4]:
t = ([1, 2], 3)
In [5]:
t[0]
Out[5]:
[1, 2]

Immutability of tuples

Tuples are immutable. That means we cannot modify their contents:

In [6]:
t[0] = 5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-8d3d8637cb4b> in <module>()
----> 1 t[0] = 5

TypeError: 'tuple' object does not support item assignment

That doesn't mean that we can't modify the contents of the contents of tuples:

In [7]:
t
Out[7]:
([1, 2], 3)
In [8]:
t[0][1] = 5
In [9]:
t
Out[9]:
([1, 5], 3)

Upacking tuples

We often want to unpack tuples. That means that for a tuple t, we want to put t[0] in one variable, t[1] in another variable, and so on. Here is how this works:

In [10]:
t = ("a", "b", "c")
i, j, k = t  #same as i = t[0], j = t[1], k = t[2]
print(i, j, k) 
a b c

Note that we have to provide the right number of variables to unpack into:

In [11]:
a, b = t
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-2d9e907c1fc9> in <module>()
----> 1 a, b = t

ValueError: too many values to unpack (expected 2)

We've actually already seen tuple unpacking, several times. Here is how we did variable swapping:

In [12]:
a = 42
b = 43
a, b = b, a   #create a new tuple (b, a), and then upack it into the variables a, b

We also saw tuple unpacking when "returning multiple objects from a function"

In [13]:
def f():
    return 42, 43

if __name__ == '__main__':
    a, b = f() #a == 42 and b == 43

Here, the function f() actually returns the tuple (42, 43), which then gets unpacked into the variables a and b. We alternatively could use f() as follows:

In [14]:
t = f()
a = t[0]
b = t[1]