Tuples

Unit 04

A new data type: tuples

We have come across tuples a few times during our first units without explaining them in more detail. For example, think back to exercise #02-04 where we applied the numpy functions concatenate and vstack:

stacked_array = np.vstack((arr1, arr2))

Mind the double parentheses. What do they mean?

Consider the following example:

# create a list and a tuple
list1 = [1, 2, 3]
tuple1 = (1, 2, 3)

# extract elements from list and tuple
print(f"This is list element 1: {list1[0]}")
print(f"This is tuple element 2 & 3: {tuple1[1:3]}")
This is list element 1: 1
This is tuple element 2 & 3: (2, 3)
# mutate list
list1[0] = -99
print(f"List element 1 got changed to: {list1[0]}")
List element 1 got changed to: -99
# try to mutate tuple
try:
    tuple1[0] = -99
except:
    print("Ooops, upon trying to change a tuple element, we got an error!")
Ooops, upon trying to change a tuple element, we got an error!
Exercise

Try to mutate a tuple yourself and find out which error you get, and what the error message says.

Tuples are immutable

Tuples are in fact very similar to lists. They are both sequences that can contain elements of different data types, which in turn can be accessed by indexing.

Their major difference is that lists are mutable, and tuples are immutable. Once a tuple is created, you cannot change single tuple elements any more. This makes tuples useful for representing collections of items that should not be altered.

Thought experiment

What other sequence data types do you know that are mutable, which are immutable?

Packing of tuples

We have just learned one way of creating a tuple, by writing a comma-separated sequence of elements that is enclosed by parentheses:

tuple1 = (1, 2, 3)

While the above is the most common approach to creating a tuple, the following approaches are also valid:

tuple2 = 4, 5, 6  # you can omit the parentheses
tuple3 = tuple()  # using a function call

Unpacking of tuples

A very useful feature of python is that you can have a tuple on the left hand side of an assignment statement. Consider the following example:

point = (3, 4)  # Tuple packing
x, y = point    # Tuple unpacking

Note that it is common practice to use parentheses in tuple packing, while it is common practice to omit the parentheses in tuple unpacking.

This feature of unpacking tuples is often used by functions that return more than one value. Consider this example from Fabien Maussion:

def split_email_address(email):
    """Splits an email address in username and domain.

    Parameters
    ----------
    email : str
        the email string

    Returns
    -------
    (username, domain): tuple of strings
    """
    return tuple(email.split('@'))

username, domain = split_email_address('john.doe@uibk.ac.at')
print(username)
print(domain)
john.doe
uibk.ac.at

Learning checklist

  • I know the difference between lists and tuples (i.e., that tuples are immutable).
  • I can pack and unpack tuples in a pythonic way, e.g., in the context of a function that returns multiple variables.
  • I know that tuples are often relevant in designing loops.