Lesson 8.3: Tuples and Immutability
What You'll Learn
- What tuples are and how they differ from lists
- How to create tuples, including single-element tuples
- How to access tuple elements with indexing and slicing
- How tuple unpacking works
- The tuple methods
count()andindex() - Why immutability matters and when it is an advantage
1. What is a Tuple?
A tuple is an ordered, immutable sequence of values. It works just like a list, except you cannot change it after it is created — no adding, removing, or modifying elements.
() or just commas. Once created, its contents cannot be changed.
# Creating a tuple with parentheses colors = ("red", "green", "blue") print(colors) print(type(colors)) # Tuples can hold mixed types record = ("Alice", 25, 3.8, True) print(record)
2. Creating Tuples
With Parentheses
point = (3, 7) weekdays = ("Mon", "Tue", "Wed", "Thu", "Fri")
Without Parentheses (Tuple Packing)
# The comma is what makes it a tuple, not the parentheses coordinates = 4, 5 print(type(coordinates))
Single-Element Tuple (The Trailing Comma)
# This is NOT a tuple - just a string in parentheses not_a_tuple = ("hello") print(type(not_a_tuple)) # This IS a tuple - note the trailing comma is_a_tuple = ("hello",) print(type(is_a_tuple))
Empty Tuple
empty = () also_empty = tuple() print(len(empty))
Converting Other Sequences to Tuples
my_list = [1, 2, 3] my_tuple = tuple(my_list) print(my_tuple) my_string = "abc" char_tuple = tuple(my_string) print(char_tuple)
3. Accessing Tuple Elements
Tuples support the same indexing and slicing as lists:
fruits = ("apple", "banana", "cherry", "date") # Indexing print(fruits[0]) print(fruits[-1]) # Slicing print(fruits[1:3]) # Length print(len(fruits)) # Membership test print("banana" in fruits)
What You Cannot Do
fruits = ("apple", "banana", "cherry") # These will all raise TypeError: # fruits[0] = "avocado" # Can't change elements # fruits.append("date") # No append method # del fruits[1] # Can't delete elements
4. Tuple Unpacking
One of the most powerful tuple features is unpacking — assigning each element to a separate variable in one line:
# Basic unpacking point = (3, 7) x, y = point print(f"x = {x}, y = {y}") # Unpacking with more values name, age, major = ("Alice", 20, "CS") print(f"{name} is {age}, studying {major}")
Swapping Variables
Tuple unpacking makes swapping values elegant:
a = 10 b = 20 # Swap without a temporary variable! a, b = b, a print(f"a = {a}, b = {b}")
Unpacking in Loops
students = [
("Alice", 95),
("Bob", 87),
("Carol", 92)
]
for name, score in students:
print(f"{name}: {score}")
ValueError.
5. Tuple Methods
Because tuples are immutable, they have only two methods:
numbers = (1, 3, 5, 3, 7, 3) # count() - how many times a value appears print(numbers.count(3)) # index() - position of first occurrence print(numbers.index(5)) print(numbers.index(3)) # first occurrence of 3
You can also use built-in functions on tuples:
nums = (10, 20, 5, 30, 15) print(min(nums)) print(max(nums)) print(sum(nums)) print(sorted(nums)) # returns a LIST, not a tuple
6. Why Immutability Matters
At first, it may seem like tuples are just limited lists. But immutability provides real benefits:
Benefits of Tuples
- Safety: Data that should not change (coordinates, RGB colors, database records) stays protected
- Dictionary Keys: Tuples can be used as dictionary keys because they are immutable; lists cannot
- Performance: Tuples are slightly faster than lists and use less memory
- Signal Intent: Using a tuple tells other programmers "this data should not be modified"
# Tuples can be dictionary keys (lists cannot!) locations = { (40.7, -74.0): "New York", (34.0, -118.2): "Los Angeles", (41.9, -87.6): "Chicago" } print(locations[(34.0, -118.2)])
Check Your Understanding
Question: Which of these creates a single-element tuple?
t = (42)t = (42,)t = [42]t = tuple(42)
Answer: b) t = (42,)
Option (a) is just the integer 42 in parentheses. Option (c) creates a list. Option (d) would raise a TypeError because tuple() expects an iterable, not a single integer.
Try It Yourself
- Create a tuple of your three favorite foods
- Use indexing to print the second food
- Try to change the first element — observe the error
- Unpack the tuple into three separate variables and print each one
- Use the tuple as a dictionary key mapped to a rating
Key Takeaways
- Tuples are ordered, immutable sequences created with
()or commas - A single-element tuple requires a trailing comma:
(value,) - Tuple unpacking assigns elements to variables in one line:
x, y = (1, 2) - Tuples have only two methods:
count()andindex() - Immutability provides safety, allows use as dictionary keys, and signals unchanging data