Tuples in Python are ordered, immutable sequences that can store heterogeneous data. Their immutability makes them ideal for representing fixed collections of values.
Creating Tuples
Tuples are defined using parantheses () with comma-separated elements. An empty tuple is created with empty parentheses, and single-element tuples require a trailing comma to distinguish them from regular parentheses used for grouping.
# Empty tuple
empty = ()
# Tuple with multiple items
colors = ("red", "green", "blue")
# Mixed data types
record = (42, "Alice", 98.6, ["math", "physics"])
print(colors) # ('red', 'green', 'blue')
print(record) # (42, 'Alice', 98.6, ['math', 'physics'])
Accessing Elements
Elements are accessed via zero-based indexing:
items = ("pen", "notebook", "ruler")
print(items[0]) # 'pen'
print(items[-1]) # 'ruler' (negative index)
Slicing
Slicing extracts subsequences with out modifying the original:
data = (10, 20, 30, 40, 50)
print(data[1:4]) # (20, 30, 40)
print(data[:3]) # (10, 20, 30)
print(data[2:]) # (30, 40, 50)
Immutability
Once created, a tuple’s contents cannot be altered:
coords = (5, 10)
# coords[0] = 7 # Raises TypeError
However, if a tuple contains mutable objects (e.g., a list), the contents of those objects can still be modified:
container = ([1, 2], "static")
container[0].append(3) # Valid
print(container) # ([1, 2, 3], 'static')
Concatenation and Repetition
Tuples support concatenation with + and repetition with *:
a = (1, 2)
b = (3, 4)
merged = a + b # (1, 2, 3, 4)
tripled = a * 3 # (1, 2, 1, 2, 1, 2)
Membership and Length
Use in to test for membership and len() for size:
values = ("x", "y", "z")
print("y" in values) # True
print(len(values)) # 3
Tuples vs Lists
| Feature | Tuple | List |
|---|---|---|
| Mutability | Immutable | Mutable |
| Syntax | ( ) |
[ ] |
| Performance | Slightly faster; hashable | Slower; not hashable |
| Use Case | Fixed data, keys in dicts | Dynamic collections |
Example illustrating differences:
# List: mutable
shopping = ["milk", "eggs"]
shopping[0] = "almond milk" # Allowed
shopping.append("bread") # Allowed
# Tuple: immutable
point = (3, 4)
# point[0] = 5 # Not allowed
# But nested mutables can change
config = ({"debug": True}, "v1.0")
config[0]["debug"] = False # Allowed