Python Tuples
Immutable sequences with tuples: creation, packing, unpacking, and when to use them over lists.
What you'll learn
- Create tuples and understand immutability
- Pack and unpack tuples for multiple values
- Use tuples as dictionary keys and set elements
- Access and slice tuples like lists
- Know when to choose tuples over lists
Concept
Creating Tuples
A tuple is an ordered, immutable sequence. Once created, you cannot add, remove, or change its elements:
empty = ()
single = (42,) # note the comma — (42) is just an int!
point = (10, 20)
mixed = (1, "hello", True)
nested = ((1, 2), (3, 4))
The trailing comma in (42,) is critical — without it, Python interprets (42) as just the integer 42 in parentheses. This is a common source of confusion for beginners.
Immutability
Tuples cannot be modified after creation:
point = (10, 20)
# point[0] = 5 # TypeError: 'tuple' object does not support item assignment
# point.append(30) # AttributeError: tuples have no append
This immutability has two benefits:
- Safety — you can be sure the data will not change accidentally
- Hashability — tuples can be used as dict keys and set elements (lists cannot)
Packing and Unpacking
Python's tuple unpacking is one of its most elegant features:
# Packing — creating a tuple
point = 10, 20 # parentheses are optional!
# Unpacking — extracting values
x, y = point
print(x, y) # 10 20
# Swap variables
a, b = 1, 2
a, b = b, a # now a=2, b=1
# Multiple return values from a function
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 4, 1, 5])
Functions that return multiple values are actually returning a tuple — Python automatically packs the values, and you unpack them on the receiving end. This is cleaner than returning a list or a custom object for simple cases.
Extended Unpacking
Python 3 introduced star unpacking for grabbing parts of a sequence:
first, *rest = [1, 2, 3, 4, 5]
# first=1, rest=[2, 3, 4, 5]
first, *middle, last = [1, 2, 3, 4, 5]
# first=1, middle=[2, 3, 4], last=5
The * collects remaining elements into a list. This is useful for ignoring or capturing variable-length portions.
Indexing and Slicing
Tuples support the same indexing and slicing as lists:
point = (10, 20, 30)
print(point[0]) # 10
print(point[-1]) # 30
print(point[0:2]) # (10, 20)
print(len(point)) # 3
Tuples as Dict Keys
Because tuples are hashable, they can be used as dictionary keys — lists cannot:
grid = {}
grid[(0, 0)] = "origin"
grid[(1, 2)] = "point A"
print(grid[(0, 0)]) # origin
This is common for coordinate-based data, sparse matrices, and caching by multiple parameters.
When to Use Tuples vs Lists
- Use a tuple for fixed collections that should not change: coordinates, RGB colors, days of the week, function returns
- Use a list when you need to add, remove, or modify elements
Tuples are also slightly faster and use less memory than lists, which matters for large datasets.
Example
# Creating tuples
empty = ()
single = (42,) # trailing comma needed for single-item tuple
point = (10, 20)
mixed = (1, "hello", True)
print(point, mixed)
# Immutability — these would raise errors:
# point[0] = 5 # TypeError
# Packing and unpacking
coordinates = 10, 20 # packing (parens optional)
x, y = coordinates # unpacking
print(f"x={x}, y={y}")
# Swap variables
a, b = 1, 2
a, b = b, a
print(f"Swapped: a={a}, b={b}")
# Multiple return values
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 4, 1, 5])
print(f"Min={low}, Max={high}")
# Extended unpacking
first, *rest = [1, 2, 3, 4, 5]
print(f"first={first}, rest={rest}")
# Tuples as dict keys
grid = {}
grid[(0, 0)] = "origin"
grid[(1, 2)] = "point A"
print(grid[(0, 0)])
# Indexing and slicing
data = (10, 20, 30, 40, 50)
print(data[0:3]) # (10, 20, 30)
print(data[::-1]) # reversed
Shows tuple creation (including the single-item comma gotcha), packing/unpacking, variable swapping, multiple return values, extended star-unpacking, tuples as dict keys, and slicing.
Try it
- JSON Formatter
Tuples serialize to JSON arrays — inspect their structure.
- Case Converter
Unpacking is useful for splitting and recombining text parts.
Common mistakes
The mistake
Writing (42) expecting a single-element tuple
The fix
(42) is just the integer 42 in parentheses. A single-element tuple requires a trailing comma: (42,). This is one of the most common tuple pitfalls for beginners.
The mistake
Trying to modify a tuple with append or item assignment
The fix
Tuples are immutable — they have no append, insert, or remove methods, and item assignment raises TypeError. If you need to modify the collection, use a list instead.
Related Resources
Related Cheatsheets
- Python Cheatsheet
Tuple creation, unpacking, and methods reference.
Practice Python Tuples
2 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.