5.1 Tuple

Contents

5.1 Tuple#

Just as strings are a sequence of characters, tuples are a sequence of objects. This makes their use far more general.

You can define tuples by using separating objects by commas:

t = 'a', 1, 'b', 2, 'c', 3

This is referred to as “tuple packing”.

Like strings, tuples can be indexed and sliced:

print('Index 3:', t[3])
print('Slice from index 3:', t[3:])
Index 3: 2
Slice from index 3: (2, 'c', 3)

Tuples are also immutable (like strings):

t[2] = 5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[3], line 1
----> 1 t[2] = 5

TypeError: 'tuple' object does not support item assignment

If you need to define a tuple with a single element, then you simply place a trailing comma:

t = 1,

print(type(t))
print(len(t))
<class 'tuple'>
1

You can also put brackets around your tuple definition. This can be useful if you want to define a tuple as a function argument, for example:

print('Tuple 1:', (1, 2, 3), 'and tuple 2:', ('a', 'b', 'c'))
Tuple 1: (1, 2, 3) and tuple 2: ('a', 'b', 'c')

Tuple Unpacking#

You can unpack a tuple into multiple variables, just like you can pack multiple values into a tuple:

t = 1, 2, 3
print('t is ', t)

x, y, z = t
print('x is', x) 
print('y is', y)
print('z is', z)
t is  (1, 2, 3)
x is 1
y is 2
z is 3

You can nest tuple unpacking if you have a tuple in a tuple, for example:

a, (b, c) = 1, (2, 3)

print('a is ', a)
print('b is ', b)
print('c is ', c)
a is  1
b is  2
c is  3

You can also unpack tuples in function calls by prefixing with *. This passes the elements of the tuple as individual arguments into the function. For example:

t = (1, 2, 3, 4)

print(*t)
1 2 3 4