Why tuples?
Programmers often want to store a whole collection of values in a single variable. Usually that means a list:
groceries = ["Eggs", "Milk", "Cheese", "Antacid"]
Lists are perfect for data that changes over time. A grocery list changes constantly depending on how much food is left in the fridge. But some data is never supposed to change. A graph of grocery trips from the 1920s is finished history: that data already happened, and no program should be able to rewrite it.
Data that never changes is called immutable, and Python has a data structure built exactly for it: the tuple (say "TOO-pull" or "TUH-pull", both are fine). A tuple is an ordered sequence of values that is locked the moment you create it. Like a display case in a museum: everyone can look at the items through the glass, in their exact order, but nobody gets to reach in and swap one out.
Vocabulary: immutable means "cannot be changed after it is created". Lists are mutable (changeable). Tuples and strings are immutable. You can always use a tuple's values to build a new tuple, but the original never changes.
Making a tuple
You create a tuple by wrapping values in parentheses, separated by commas:
# an x, y coordinate on a graph data_point = (12342, 4) print(data_point) # parentheses are actually optional: the commas make the tuple data_point2 = 435, 3 print(data_point2)
(12342, 4) (435, 3)
There is one sneaky special case. To make a tuple with only one value, you must include a comma after the value. Without the comma, Python thinks the parentheses are just regular math parentheses and gives you a plain number instead:
single_tuple = (234,) # the comma makes it a tuple not_a_tuple = (234) # no comma: just the number 234 print(type(single_tuple)) print(type(not_a_tuple))
<class 'tuple'> <class 'int'>
Remember the comma! (234,) is a one-item tuple. (234) is just the number 234 wearing parentheses. The comma, not the parentheses, is what makes a tuple.
Reading a tuple
Reading a tuple works exactly like reading a list or a string. Every value has an index (its numbered position, starting at 0), and you grab a value with square brackets:
movies_from_2019 = ("Us", "Once Upon a Time in Hollywood") print(movies_from_2019[0]) # index 0 is the FIRST value print(len(movies_from_2019)) # len() counts the values
Us 2
Two more reading tools work on tuples just like they do on lists:
- value in my_tuple checks membership: it gives True if the value is somewhere in the tuple, False if not.
- my_tuple.index(value) tells you where a value sits, returning its index number.
movies_from_2019 = ("Us", "Once Upon a Time in Hollywood") print("Us" in movies_from_2019) print("Frozen II" in movies_from_2019) print(movies_from_2019.index("Us"))
True False 0
Careful: asking index() for a value that is not in the tuple crashes your program with a ValueError. When you are not sure a value is there, check with in first.
Sealed shut: immutability
Here is where tuples split from lists. With a list, you can reach into any slot and change it. Try that with a tuple and Python slams the glass shut. This program crashes:
gold = (255, 215, 0) # the RGB color gold gold[1] = 0 # try to change the green value...
Traceback (most recent call last):
File "main.py", line 2, in <module>
gold[1] = 0
TypeError: 'tuple' object does not support item assignment
That TypeError is not Python being grumpy. It is Python protecting your data. If a value is stored in a tuple, you have a guarantee that no line of code, anywhere in your program, ever changed it by accident. That guarantee is exactly what you want for data like this:
Coordinates
A point on a graph or map is one fixed spot. If some code could nudge the x value, it would be a different point.
home = (39.5, -98.3)RGB colors
The color gold is always the same recipe of red, green, and blue. Change one number and it is not gold anymore.
gold = (255, 215, 0)Birthdays
Your birthday happened once and is never getting edited. Historical data belongs behind glass.
bday = (2012, 3, 14)Rule of thumb: if the data is supposed to change (a grocery list, a high score table), use a list. If the data should stay exactly as it was created (a coordinate, a color, a date), use a tuple and let Python stand guard.
Lists vs tuples lab
Time to see the difference with your own hands. Below, the same three colors are stored twice: once in a list (an open shelf) and once in a tuple (a glass display case). Every button tries the same operation on both sides. Watch which side goes along with it, and read the exact Python that ran under each panel.
Lists vs tuples lab
same data, two containersOpen shelf list, mutable
Anyone can rearrange it.
colors_list = ["red", "green", "blue"]
Glass case tuple, immutable
Look all you want. No touching.
colors_tuple = ("red", "green", "blue")
Try the same operation on both
Reads work everywhere. Changes only work on the shelf. The value box feeds the change and add buttons.
Notice what the errors say. Changing a slot raises TypeError: 'tuple' object does not support item assignment, and tuples do not even have an append method to call. The glass case is sealed from every angle.
Practice: science pairs
Science Pairs
A science class paired students together for the whole school year and stored each pairing in a tuple. Then two students moved to Arkansas mid-year, so new pairs are needed. The tuples cannot be edited, but you can read them and build a new one:
- Index into the tuples to pull out the names "Ernesto" and "Gabby".
- Create a new tuple containing those two names.
- Print the new tuple to the console.
# Existing pairs group_1 = ("Samantha", "Kevin") group_2 = ("Ernesto", "Damiyr") group_3 = ("Bianca", "Gabby") # Store the values Ernesto and Gabby by indexing their tuples # Create a new tuple with Ernesto and Gabby # Print the new tuple to the console
# Existing pairs group_1 = ("Samantha", "Kevin") group_2 = ("Ernesto", "Damiyr") group_3 = ("Bianca", "Gabby") # Ernesto is first in group_2, Gabby is second in group_3 ernesto = group_2[0] gabby = group_3[1] # Create a new tuple with Ernesto and Gabby group_4 = (ernesto, gabby) # Print the new tuple to the console print(group_4)
('Ernesto', 'Gabby')
Note what happened: the old tuples never changed. You read values out of them and built a brand new tuple. That is the tuple way: never edit, always build fresh.
Combining and unpacking
Immutable does not mean useless. Tuples and their values can be used to create other tuples. Adding two tuples with + glues them into a bigger, brand new tuple:
tuple_one = (1, 2) tuple_two = (3, 4) tuple_three = tuple_one + tuple_two print(tuple_three)
(1, 2, 3, 4)
You can also do the reverse: take a tuple apart and pour each value into its own variable, all in one line. This is called sequence unpacking. Writing values into a tuple is sometimes called packing; unpacking is the trip back out:
tuple_one = ("Reverse", "Me") string_one, string_two = tuple_one print(string_two, string_one)
Me Reverse
The values land in the variables in the same order they sit in the tuple: string_one gets "Reverse", string_two gets "Me". Unpacking makes it easy to use a tuple's contents without ever changing the tuple itself.
Practice: rare books
Alice in Wonderland
A bookstore used to own exactly one copy of a rare collector's edition of "Alice in Wonderland". Recently they got two more copies! The catalog is stored in tuples, so you cannot append. Instead:
- Create a new tuple that includes two copies of "Alice in Wonderland".
- Then create a third tuple that also includes "Alice's Adventures in Wonderland" (one of the new copies turned out to be a special edition).
book_collection = ("Alice in Wonderland",) # Create a new tuple with two copies of the book: # Create a third tuple with the book "Alice's Adventures in Wonderland"
book_collection = ("Alice in Wonderland",) # Adding the one-book tuple to itself makes a two-copy tuple two_copies = book_collection + book_collection print(two_copies) # Add a one-item tuple with the special edition (note the comma!) full_collection = two_copies + ("Alice's Adventures in Wonderland",) print(full_collection)
('Alice in Wonderland', 'Alice in Wonderland')
('Alice in Wonderland', 'Alice in Wonderland', "Alice's Adventures in Wonderland")
Spot the single-value tuple trick? ("Alice's Adventures in Wonderland",) needs that trailing comma. Without it, Python would try to add a tuple to a plain string and crash.
Looping over a tuple
Just like lists, tuples work with a for loop. The loop visits every value, in order, from behind the glass. Reading is always allowed:
tuple_iteration = ("Karel", "Tracy", "Calvin") for item in tuple_iteration: print(item)
Karel Tracy Calvin
Practice: zoo loan
Zoo Animals
A zoo stores all of its animals in a tuple. The zoo decided to loan every animal whose name starts with the letter c to the Crazy Cool Circus Collective. Using a for loop, iterate through the tuple and count how many animals need to be loaned out.
zoo_animals = ("cat", "koala", "tiger", "crocodile", "elephant", "camel", "giraffe", "kangaroo", "catfish", "chimpanzee", "caterpillar", "duck") # Iterate through the tuple and count all animals that start with the letter c
zoo_animals = ("cat", "koala", "tiger", "crocodile", "elephant", "camel", "giraffe", "kangaroo", "catfish", "chimpanzee", "caterpillar", "duck") count = 0 for animal in zoo_animals: if animal[0] == "c": count = count + 1 print("Animals to loan out:", count)
Animals to loan out: 6
Count them yourself: cat, crocodile, camel, catfish, chimpanzee, and caterpillar. Indexing works inside the loop too: animal[0] is the first letter of each name, because strings are indexed just like tuples.
Converting: list() and tuple()
What if data starts out changeable and then needs to be locked, or the other way around? Python gives you two converter functions. Each one builds a brand new container; the original is never touched:
- tuple(my_list) makes a sealed tuple copy of a list. Great for freezing a finished result.
- list(my_tuple) makes an editable list copy of a tuple. Great when you need a working copy you can change.
draft_scores = [88, 92, 79] # still being edited... a list final_scores = tuple(draft_scores) # grades are in: freeze them! print(final_scores) working_copy = list(final_scores) # need to experiment? thaw a COPY working_copy.append(100) print(working_copy) print(final_scores) # the frozen original is untouched
(88, 92, 79) [88, 92, 79, 100] (88, 92, 79)
Key idea: converting never unlocks the original tuple. list(final_scores) hands you a fresh, editable copy, while final_scores itself stays sealed forever. You saw the same thing with the convert buttons in the lab above.
Think you can tell your shelves from your display cases? Prove it below.
Quick quiz
1. What happens when this program runs?
point = (3, 8) point[0] = 5
2. Which line creates a tuple containing just the single value 7?
3. What does this program print?
pair = ("hi", "bye") a, b = pair print(b, a)
Keep learning Python
Tuples lock a sequence behind glass. Head back to lists for data that needs to change, or meet dictionaries, which label every value with a key instead of an index.