Tuples
Overview
Tuples are structurally identical to lists, but with one critical difference: they are IMMUTABLE. Once a tuple is created, its contents can never be added to, removed, or modified. Why use them? Because they cannot change, Python can heavily optimize them. They take up less memory, iterate slightly faster, and most importantly, they are 'hashable'. This means tuples (unlike lists) can be used as keys in dictionaries or stored in Sets. They are typically used to group related, heterogenous data, like X/Y coordinates.
Syntax
# Creating tuples (Parentheses are optional but recommended)
point = (10, 20)
rgb_color = 255, 128, 0
# Accessing elements works exactly like lists
print(point[0]) # 10
# IMMUTABLE: This will instantly throw a TypeError
# point[0] = 15
# Tuple Unpacking (Highly common in Python)
x, y = point
print(f"X is {x}, Y is {y}")Common Pitfalls
- Defining a single-element tuple incorrectly. Writing
t = (5)just creates an integer wrapped in math parentheses. You MUST include a trailing comma to define a tuple:t = (5,). - Believing tuples are 'deeply' immutable. If a tuple contains a mutable object (like a list), you cannot reassign the list, but you CAN mutate the list's contents:
t = ([1], 2); t[0].append(99)is perfectly legal.
Interview Questions
When you have a fixed collection of data that should act as a constant (preventing accidental mutation), or when you need a composite key for a dictionary (e.g., mapping (x, y) coordinate tuples to values).
Real-World Example
Functions in Python use tuples behind the scenes to return multiple values seamlessly.
def get_user_data(user_id):
# Python automatically packs these return values into a tuple
return "Alice", "admin", 28
# We unpack the tuple directly into three variables
name, role, age = get_user_data(99)
print(f"{name} is an {role}.")Check Your Knowledge
Test your understanding of Tuples with these quick questions.