How do tuples differ from lists in Python?
· Category: Python Programming
Short answer
Tuples are immutable, ordered sequences, while lists are mutable. Because tuples cannot change after creation, they can be used as dictionary keys and are slightly more memory-efficient and faster to create.
Key differences
- Mutability: Lists can be modified; tuples cannot.
- Syntax: Lists use
[]; tuples use()(or no brackets for packing). - Hashability: Tuples are hashable if their contents are hashable; lists are never hashable.
- Performance: Tuples have a smaller memory footprint and faster instantiation.
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
my_list[0] = 10 # OK
# my_tuple[0] = 10 # TypeError
# Tuples as dict keys
locations = {
(0, 0): "origin",
(1, 0): "east"
}
When to use each
- Use lists when you need a collection that will change over time.
- Use tuples for fixed collections, record-like structures, or dictionary keys.
- Use named tuples (
collections.namedtupleortyping.NamedTuple) for readable, lightweight data classes.
Example
Tuple unpacking is a powerful Python feature:
point = (10, 20)
x, y = point
print(x, y)
# Multiple return values
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 4, 1, 5])
print(low, high)
Common issues
- A single-item tuple requires a trailing comma:
(1,)instead of(1). - Trying to modify a tuple raises a
TypeError, but mutable objects inside a tuple (like lists) can still be changed.