CSci 150: Foundations of computer science
Home Syllabus Readings Projects Tests

Tuples

What tuples are

A tuple is a composite data type that is similar to a list except that — as we'll discuss later — it cannot be changed after creation. Recall that you can do the following with a list:

prime_list = [235711]
print(len(prime_list))   # displays 5
print(prime_list[3])     # displays 7

Rather than have use a list, though, we could just as easily done this with tuples: The only change is to create the tuples using parentheses rather than brackets. (You still use brackets to look up an individual slot of the tuple, though.)

prime_tuple = (235711)
print(len(prime_tuple))  # displays 5
print(prime_tuple[3])    # displays 7

The key difference between lists and tuples is that tuples cannot be modified. We can do the following with a list:

prime_list[4] = 13
prime_list.append(17)

Both of these change the contents of the list. Both would be prohibited if attempted on a tuple.

Why use tuples?

Of course, tuples are strictly “weaker” than lists. Why, then, use tuples when you could use lists?

First, typically tuples are more suitable for conglomerations of different types of data on the same sort of thing, whereas lists make more sense when we have a number of related elements. For enumerating prime numbers, then, a list would make more sense; but if we wanted to create a single data that incorporates a city's name with its state and population, a programmer would tend to look toward a list with the city's name in the first spot, the state name in the second, and the population in the third. Admittedly, we could use a list for that, but generally a tuple makes more sense.

More pragmatically, one very particular scenario where you must use a tuple instead of a list is as the key to a dictionary. Dictionaries forbid lists to act as a key, since once it places a key-value pair into a bucket, it has no way of detecting when the key has changed and so belongs into a different bucket. Tuples (and strings and integers) cannot change, so they are valid keys. A case where you might want a tuple as a key is a dictionary where you want to save the current population for each city-state combination: The key would be a tuple containing the city name in the first position and the state name in the second position.