Tuples and Immutability
Understand tuples and why some data should never change
Tuples and Immutability
What is a Tuple?
Think of a tuple like a sealed envelope. Once you put items inside and seal it, you cannot change what's inside.
A tuple in Python is like a list, but with one big difference: after you create it, you cannot change it. You cannot add items, remove items, or modify items.
Why use tuples instead of lists?
- Protect data that should never change (like dates, coordinates)
- Faster than lists for Python to work with
- Can be used as dictionary keys (lists cannot)
- Show other programmers this data is fixed
Creating a Tuple
You create a tuple using parentheses instead of square brackets.
coordinates = (10, 20)
print(coordinates)What happens: Python creates a tuple with 2 numbers. These numbers cannot be changed later.
Different ways to create tuples:
- Multiple items with parentheses
colors = ("red", "blue", "green")- Without parentheses (Python understands)
colors = "red", "blue", "green"- Single item tuple (need a comma)
single = (5,)Important: For one item, you must include a comma. Without it, Python thinks it's just a number in parentheses.
- Empty tuple
empty = ()Accessing Tuple Items
Tuples work like lists for reading data. You use index numbers starting from 0.
point = (10, 20, 30)
print(point[0])
print(point[1])
print(point[-1])What this shows:
- point[0] gives 10 (first item)
- point[1] gives 20 (second item)
- point[-1] gives 30 (last item)
Understanding Immutability
Immutability means "cannot be changed". Once a tuple is created, it stays that way forever.
This works with tuples:
numbers = (1, 2, 3)
print(numbers[0])
print(len(numbers))
print(2 in numbers)This does NOT work with tuples:
numbers = (1, 2, 3)
numbers[0] = 5 # Error! Cannot change tuple
numbers.append(4) # Error! Cannot add to tuple
numbers.remove(1) # Error! Cannot remove from tupleWhy this matters: When you see a tuple in code, you know that data is safe and won't change. This makes your programs more predictable and prevents bugs.
When to Use Tuples vs Lists
Use a tuple when:
- Data should never change (birthdate, coordinates, RGB colors)
- You want to protect data from accidental changes
- You need slightly better performance
- You want to use it as a dictionary key
Use a list when:
- You need to add or remove items
- You want to sort or modify data
- Data will change over time
Real-world examples:
birthday = (1995, 8, 15)
rgb_color = (255, 0, 128)
location = (40.7128, -74.0060)
shopping_list = ["milk", "eggs", "bread"]What's the difference:
- Birthday, color, and location should never change, so use tuples
- Shopping list will change (add items, remove items), so use list
Tuple Operations
Even though you cannot change a tuple, you can still do many things with it.
Counting Length
point = (10, 20, 30)
print(len(point))Shows: 3
Checking if Item Exists
colors = ("red", "blue", "green")
print("red" in colors)
print("yellow" in colors)Shows: True, then False
Combining Tuples
You can join tuples to create a new tuple.
tuple1 = (1, 2)
tuple2 = (3, 4)
combined = tuple1 + tuple2
print(combined)Result: (1, 2, 3, 4)
Important: This doesn't change the original tuples. It creates a completely new tuple.
Repeating Tuples
pattern = (1, 2)
repeated = pattern * 3
print(repeated)Result: (1, 2, 1, 2, 1, 2)
Counting Items
numbers = (1, 2, 2, 3, 2)
print(numbers.count(2))Shows: 3 (the number 2 appears three times)
Finding Position
colors = ("red", "blue", "green")
print(colors.index("blue"))Shows: 1 (blue is at position 1)
Tuple Unpacking
Unpacking means taking items out of a tuple and putting them into separate variables. This is very useful.
point = (10, 20)
x = point[0]
y = point[1]Easier way using unpacking:
point = (10, 20)
x, y = point
print(x)
print(y)What happens: Python automatically takes 10 and puts it in x, takes 20 and puts it in y.
Real-world example:
person = ("John", 25, "Engineer")
name, age, job = person
print("Name:", name)
print("Age:", age)
print("Job:", job)This is much cleaner than using index numbers.
Practice Example
The scenario: You're building a map application. You store locations as tuples because coordinates never change.
home = (40.7128, -74.0060)
work = (40.7589, -73.9851)
lat1, lon1 = home
lat2, lon2 = work
print("Home location:", lat1, lon1)
print("Work location:", lat2, lon2)
locations = (home, work)
print("Total locations:", len(locations))
if home in locations:
print("Home saved successfully")What this program does:
- Creates two coordinate tuples (cannot be changed)
- Unpacks home coordinates into lat1 and lon1
- Unpacks work coordinates into lat2 and lon2
- Creates a tuple containing both locations
- Counts total locations
- Verifies home location is saved
Key Points to Remember
Tuples are like lists but cannot be changed after creation. Use parentheses to create them, and include a comma for single-item tuples.
Tuples are immutable, meaning you cannot add, remove, or modify items. This protects important data from accidental changes.
Use tuples for data that should stay constant like coordinates, dates, or configuration values. Use lists for data that needs to change.
Tuples support reading operations like indexing, counting, checking membership, and combining, but not modifying operations.
Tuple unpacking lets you extract items into separate variables in one line, making code cleaner and easier to read.
Common Mistakes
Mistake 1: Forgetting comma for single item
single = (5) # This is just number 5
single = (5,) # This is a tuple with one itemMistake 2: Trying to modify tuple
colors = ("red", "blue")
colors[0] = "green" # Error! Tuples cannot changeMistake 3: Wrong number of variables in unpacking
point = (10, 20, 30)
x, y = point # Error! 3 items but only 2 variablesCorrect way:
x, y, z = point # Now it worksWhat's Next?
Now you understand tuples and why immutability matters. Next, you'll learn about dictionaries - a powerful way to store data using key-value pairs instead of positions.