Tuples & Immutability
Understand Tuples: the read-only cousins of Lists. Learn why immutability matters for performance and code safety.
What is a Tuple?
A tuple looks and behaves very much like a list, but with one massive difference: Tuples are immutable. Once you create a tuple, you can never change, add, or remove items from it.
# Tuples use parentheses
coordinates = (34.0522, -118.2437)Why Use Tuples?
If you can't change them, why not just use a List?
- Performance: Because Python knows the data will never change, tuples are stored more efficiently in memory and iterate slightly faster than lists.
- Safety: If you are passing crucial data (like database credentials or geographic coordinates) around your application, a tuple guarantees that a stray function won't accidentally overwrite the data.
- Dictionary Keys: Because they are immutable, tuples can be used as keys in a dictionary (Lists cannot!).
Tuple Unpacking
Python allows you to elegantly unpack the contents of a tuple directly into separate variables in a single line.
user_data = ("Alice", 28, "Engineer")
# Unpacking
name, age, profession = user_data
print(f"{name} is a {age}-year-old {profession}.")