5.0 Tuples

A tuple is a sequence of values. These values can be of any data type, and they are indexed by integers, just like lists. The key difference between tuples and lists is that the former are immutable.

5.1 Basics

Here are some ways to write tuples:

In [1]:
# the two tuples defined below are syntactically equivalent:

t1 = 'A', 'B', 'C', 'D', 'E'

t2 = ('A', 'B', 'C', 'D', 'E')    # parentheses are optional

If you want to have a tuple with a single element, make sure you include a final comma:

In [3]:
t3 = 'G',     # NOTE that t3 = ('G') is a string, not a tuple.....
              #      but t3 = ('G',) is a tuple
In [8]:
# you can convince yourself that t1, t2, t3 are tuples
# by checking them with the built-in 'type' function:

# type(t1)
# type(t2)
type(t3)
Out[8]:
tuple

Tuples can also be created with a Python built-in function called tuple.

In [9]:
t4 = tuple()   # have created an empty tuple
type(t4)
Out[9]:
tuple
In [11]:
t4.append('A')    # this was to be expected....
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-bd7f8db43a7a> in <module>()
----> 1 t4.append('A')

AttributeError: 'tuple' object has no attribute 'append'

Because tuples are immutable, you can't modify them. The built-in function 'append' available for lists does not work here (as can be clearly seen from the above error message).

Tuples are iterable, as the next example shows:

In [12]:
for item in t1:
    print(item)
A
B
C
D
E
In [13]:
len(t1)   # use 'len' to find the number
          # of elements in a tuple
Out[13]:
5

To access individual elements in a tuple, use the syntax introduced for lists: the name of the tuple followed by a pair of square brackets enclosing the index number. Recall that the index associated with the first element is 0, the index of the second element is 1, and so on. The next example should clarify these observations:

In [14]:
for i in range(len(t1)):
    print(i, t1[i])
0 A
1 B
2 C
3 D
4 E

5.2 Tuple assignment

Swapping two variables in a computer program requires the introduction of a temporary variable to hold one of the values while the swapping is carried out. In the next example we swap the place of $x$ and $y$ by using the temporary variable 'tmp':

In [15]:
# swapping values stored in two variables:
    
x = 5; y = 7
print('x is: ', x, 'and','y is: ', y)

tmp = x
x = y
y = tmp

# check to see what happened...
print('x is: ', x, 'and','y is: ', y)
x is:  5 and y is:  7
x is:  7 and y is:  5
In [16]:
# same as above, a tuple implementation....
x = 5; y = 7
print('x is: ', x, 'and','y is: ', y)

x, y = y, x     # this is the equivalent of the three lines above
                # no temporary variable is needed....

# check to see the result ....    
print('x is: ', x, 'and','y is: ', y)
x is:  5 and y is:  7
x is:  7 and y is:  5

The way this works: in the last example, the LHS is a tuple of variables, the RHS a tuple of values. Each value is assigned to the corresponding variable because Python supports multiple assignments (i.e., several variables are assigned values by using just one assignment operator).

One of the most interesting functions in the context of tuples is the built-in zip function. This function, used in conjunction with the built-in tuple function, takes two or more tuples and produces a list of tuples where each tuple contains one element from each sequence/tuple. Here is a simple example of how it works:

In [21]:
names = ('John', 'Fred', 'Mustafa', 'Yolanda')           # list of 4 students
modules = ('MATH001', 'MATH101', 'MATH001', 'MATH321')   # list of 4 modules

# define a list which contains tuple of the form 
# (name[i], module[i]) for i=0, 1, 2, 3

tmp = zip(names, modules)
names_and_modules = tuple(tmp)    # you can iterate through 'names_and_modules', etc

print(names_and_modules) 
(('John', 'MATH001'), ('Fred', 'MATH101'), ('Mustafa', 'MATH001'), ('Yolanda', 'MATH321'))

This approach can be used to organise a set of points in the plane. You can store the x-coordinates in a tuple X (say), the y-coordinates in another tuple Y (say), then you zip them together and generate a new tuple P (say) that stores the actual $(x,y)$ pairs for all the points in your set; the points will be P[0], P[1], P[2], and so on.



REFERENCE:

T. Gaddis, Starting out with Python (Fourth Edition), Pearson Education Ltd., 2018