Python Tuples: When and Why to Use Immutable Sequences
Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย
Think about GPS coordinates. A location like (40.7128, -74.0060) represents New York City. If you accidentally changed one of those numbers, the location would point somewhere completely different. Some data simply should not change after you create it.
Dates work the same way. January 1st, 2025 is a fixed fact. You wouldn't want code to accidentally modify that date to February 37th. When data needs to stay locked in place, Python gives you tuples.
A tuple looks almost identical to a list, but with one critical difference: once you create a tuple, you cannot change it. No adding, removing, or swapping items. In this tutorial, you'll learn why that limitation is actually a superpower.
How to Create Tuples in Python
You create a tuple by putting items inside parentheses (), separated by commas. You can also create a tuple without parentheses - the commas are what actually make it a tuple.
(40.7128, -74.006)
('red', 'green', 'blue')
(42,)
<class 'tuple'><class 'int'> <class 'tuple'> () 0
You can also convert other sequences into tuples using the tuple() constructor. This is handy when you have a list and want to freeze it so nobody can modify it.
('apple', 'banana', 'cherry')
('h', 'e', 'l', 'l', 'o')Accessing and Slicing Tuple Elements
Accessing tuple items works exactly like lists. You use square brackets with an index number. Positive indexes count from the front, negative indexes count from the back.
Jan Apr Jun May 6
Slicing also works the same way. You can grab a portion of a tuple with tuple[start:end]. The result is a new tuple.
('Feb', 'Mar', 'Apr')
('Jan', 'Feb', 'Mar')
('May', 'Jun')
('Jan', 'Mar', 'May')But here is where tuples differ from lists. If you try to change an item, Python will raise a TypeError. Tuples are immutable - they cannot be modified after creation.
red
Tuple Packing and Unpacking
('Alice', 25, 'Engineer')
Alice
25
EngineerThe number of variables on the left must match the number of items in the tuple. If they don't match, Python raises a ValueError.
A classic use of unpacking is swapping two variables without needing a temporary variable. Most other languages require three lines for this - Python does it in one.
Before: a=10, b=20 After: a=20, b=10
You can also use a star * to capture leftover items when unpacking. This is called extended unpacking and it gives you a list of the remaining items.
95 [87, 72, 68] 91
Alice scored 95 Bob scored 87 Charlie scored 72
Tuples vs Lists: When to Use Each
If tuples are just lists that you can't change, why bother with them? There are three solid reasons: safety, performance, and dictionary keys.
Safety: When data shouldn't change, a tuple prevents accidental modifications. GPS coordinates, RGB color values, database records - these are fixed facts. A tuple makes your intent clear.
Performance: Tuples are slightly faster than lists and use less memory. For small collections this barely matters, but it adds up with millions of records.
Dictionary keys: Tuples can be used as dictionary keys because they are immutable. Lists cannot. This becomes important when you learn about dictionaries.
# Data that changes over time
shopping = ['milk', 'eggs']
shopping.append('bread')
# Collections you sort or filter
scores = [85, 92, 78]
scores.sort()# Fixed data that shouldn't change
coords = (40.7128, -74.0060)
rgb_red = (255, 0, 0)
# Returning multiple values
def get_name_age():
return 'Alice', 25Under the Hood: Why Tuples Are Faster Than Lists
Because tuples are immutable, Python can make behind-the-scenes optimizations. A tuple's size is fixed at creation, so Python stores it in one compact block. A list carries extra bookkeeping so it can grow, and it often reserves spare room for new items.
List size: 52 bytes Tuple size: 40 bytes
Tuples also support all the same operations that don't modify the sequence. You can use count() to count occurrences, index() to find the position of a value, in to check membership, and + to concatenate.
3 2 True (1, 2, 3, 4)
Practice Exercises
Time to practice! These exercises cover tuple creation, unpacking, and understanding immutability.
Create a tuple called seasons containing the four seasons as strings: 'Spring', 'Summer', 'Fall', 'Winter'.
Then print the first and last season, each on its own line.
Expected output:
Spring
WinterRead this code carefully. What will it print? Think about what makes something a tuple versus a plain number in parentheses.
a = (5)
b = (5,)
print(type(a).__name__)
print(type(b).__name__)Write two print() statements that produce the exact same output.
A tuple representing a student record is given. Unpack it into three variables: name, age, and grade.
Then print each variable on its own line.
Expected output:
Emma
16
AThis code tries to change a color in a tuple, but tuples are immutable. Fix it so the program prints the updated colors without changing the original tuple. Create a new tuple instead.
Expected output:
('red', 'yellow', 'blue')You have a list of tuples, where each tuple contains a student name and their score. Loop through the list, unpack each tuple, and print each student's result in this format:
Alice: 92
Bob: 85
Charlie: 78A robot starts at (0, 0). It gets a list of moves, each a tuple (direction, steps): "N" adds 1 to y for each step, "S" takes 1 away, "E" adds 1 to x and "W" takes 1 away. The robot walks one square at a time.
Write a function first_repeat(moves) that returns the first point the robot reaches for the second time, as a tuple (x, y), or None if it never visits a point twice. The starting point counts as visited.
first_repeat([("E", 3), ("N", 1), ("W", 1), ("S", 3)]) # (2, 0)Walking east the robot passes (1, 0), (2, 0) and (3, 0). Walking south from (2, 1) it reaches (2, 0) again.
Return the answer instead of printing it: Check prints what first_repeat() returns for its own moves, some of them hidden.
Summary: What You Learned About Python Tuples
Here's a recap of everything you now know about tuples:
| Concept | What it does | Example |
|---|---|---|
| Create a tuple | Store fixed items | point = (3, 4) |
| Trailing comma | Make single-item tuple | solo = (42,) |
| Indexing | Access by position | point[0], point[-1] |
| Slicing | Get a portion | months[1:4] |
| Unpacking | Extract into variables | x, y = point |
| Extended unpacking | Capture extras with * | first, *rest = items |
count() | Count occurrences | t.count(2) |
index() | Find position | t.index(3) |
| Immutability | Cannot modify after creation | Raises TypeError |
Tuples are perfect for fixed collections of data - coordinates, colors, records, and function return values. Their immutability makes your code safer and your intentions clearer.
What's Next?
In the next tutorial - Python Dictionaries - you'll learn how to store data as key-value pairs. Instead of accessing items by position, you'll access them by name.
Dictionaries are one of the most powerful data structures in Python. Combined with lists and tuples, they let you model almost any real-world data.