Skip to main content
Editor

Python Tuples: When and Why to Use Immutable Sequences

Beginner20 min6 exercises90 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/6 exercises

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.

Creating tuples
# Tuple with parentheses
coordinates = (40.7128, -74.0060)
print(coordinates)
# Tuple without parentheses (commas do the work)
colors = 'red', 'green', 'blue'
print(colors)
# Single-item tuple NEEDS a trailing comma
single = (42,)
print(single) # (42,)
print(type(single)) # <class 'tuple'>
Output
(40.7128, -74.006)
('red', 'green', 'blue')
(42,)
<class 'tuple'>
Single-item tuple vs parenthesized expression
# This is NOT a tuple
not_a_tuple = (42)
print(type(not_a_tuple)) # <class 'int'>
# This IS a tuple
is_a_tuple = (42,)
print(type(is_a_tuple)) # <class 'tuple'>
# Empty tuple
empty = ()
print(empty) # ()
print(len(empty)) # 0
Output
<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.

Using the tuple() constructor
# Convert a list to a tuple
fruit_list = ['apple', 'banana', 'cherry']
fruit_tuple = tuple(fruit_list)
print(fruit_tuple) # ('apple', 'banana', 'cherry')
# Convert a string to a tuple of characters
letters = tuple('hello')
print(letters) # ('h', 'e', 'l', 'l', 'o')
Output
('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.

Indexing tuples
months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun')
# Positive indexing
print(months[0]) # Jan
print(months[3]) # Apr
# Negative indexing
print(months[-1]) # Jun
print(months[-2]) # May
# Length
print(len(months)) # 6
Output
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.

Slicing tuples
months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun')
# Slice from index 1 to 4 (not including 4)
print(months[1:4]) # ('Feb', 'Mar', 'Apr')
# First three
print(months[:3]) # ('Jan', 'Feb', 'Mar')
# Last two
print(months[-2:]) # ('May', 'Jun')
# Every other month
print(months[::2]) # ('Jan', 'Mar', 'May')
Output
('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.

Tuples are immutable
colors = ('red', 'green', 'blue')
# This works fine - reading
print(colors[0]) # red
# This will CRASH - writing
# colors[0] = 'yellow' # TypeError: 'tuple' object does not support item assignment
# Uncomment the line above and run it to see the error!
Output
red

Tuple Packing and Unpacking

Packing is when you create a tuple by assigning multiple values to one variable. Unpacking is the reverse - pulling individual values out of a tuple into separate variables. Unpacking is one of the most useful features in Python.

Packing and unpacking
# Packing - multiple values into one tuple
person = 'Alice', 25, 'Engineer'
print(person) # ('Alice', 25, 'Engineer')
# Unpacking - one tuple into multiple variables
name, age, job = person
print(name) # Alice
print(age) # 25
print(job) # Engineer
Output
('Alice', 25, 'Engineer')
Alice
25
Engineer

The 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.

Swapping variables with tuple unpacking
a = 10
b = 20
print(f'Before: a={a}, b={b}')
# Swap using tuple unpacking
a, b = b, a
print(f'After: a={a}, b={b}')
Output
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.

Extended unpacking with the star operator
scores = (95, 87, 72, 68, 91)
# Grab the first, last, and everything in between
first, *middle, last = scores
print(first) # 95
print(middle) # [87, 72, 68]
print(last) # 91
Output
95
[87, 72, 68]
91
Unpacking tuples in a for loop
students = [
('Alice', 95),
('Bob', 87),
('Charlie', 72),
]
for name, score in students:
print(f'{name} scored {score}')
Output
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.

Use a List when...
# Data that changes over time
shopping = ['milk', 'eggs']
shopping.append('bread')

# Collections you sort or filter
scores = [85, 92, 78]
scores.sort()
Use a Tuple when...
# 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', 25

Under 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.

Comparing memory usage
import sys
# Compare memory usage
my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3, 4, 5)
print(f'List size: {sys.getsizeof(my_list)} bytes')
print(f'Tuple size: {sys.getsizeof(my_tuple)} bytes')
Output
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.

Tuple methods and operations
numbers = (1, 2, 3, 2, 4, 2)
# count() - how many times a value appears
print(numbers.count(2)) # 3
# index() - position of first occurrence
print(numbers.index(3)) # 2
# in - membership check
print(4 in numbers) # True
# Concatenation creates a NEW tuple
combined = (1, 2) + (3, 4)
print(combined) # (1, 2, 3, 4)
Output
3
2
True
(1, 2, 3, 4)

Practice Exercises

Time to practice! These exercises cover tuple creation, unpacking, and understanding immutability.

Exercise 1: Create a Tuple and Access Elements
Write Code

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
Winter
# Create the seasons tuple
# Print the first season
# Print the last season
Exercise 2: Predict the Output: Single Item Tuple
Predict Output

Read 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.

# Predict the output and write the matching print statements
print("?")
print("?")
Exercise 3: Unpack a Tuple
Write Code

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
A
student = ('Emma', 16, 'A')
# Unpack the tuple into name, age, grade
# Print each variable
Exercise 4: Fix the Bug: Modifying a Tuple
Fix the Bug

This 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')
colors = ('red', 'green', 'blue')
colors[1] = 'yellow'
print(colors)
Exercise 5: Loop and Unpack Student Scores
Write Code

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: 78
students = [
('Alice', 92),
('Bob', 85),
('Charlie', 78),
]
# Loop through and print each student's result
Where the Path Crosses
Stretch

A 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.

def first_repeat(moves):
pass
Solution unlocks after your first Check

Summary: What You Learned About Python Tuples

Here's a recap of everything you now know about tuples:

ConceptWhat it doesExample
Create a tupleStore fixed itemspoint = (3, 4)
Trailing commaMake single-item tuplesolo = (42,)
IndexingAccess by positionpoint[0], point[-1]
SlicingGet a portionmonths[1:4]
UnpackingExtract into variablesx, y = point
Extended unpackingCapture extras with *first, *rest = items
count()Count occurrencest.count(2)
index()Find positiont.index(3)
ImmutabilityCannot modify after creationRaises 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.

Harder problems

More problems on this topic: Data structures

Related Tutorials

Was this tutorial helpful?