Tuples in Python
Learning objectives
By the end of this pill you will be able to:
- create and initialise tuples (
tuple); - access elements by index;
- understand tuple immutability;
- use tuples for multiple assignments and as dictionary keys;
- clearly distinguish tuples from lists and sets.
What is a tuple
A tuple is an ordered and immutable collection of elements.
It is created with round parentheses ( ) or with the tuple() function.
coordinates = (10, 20)
colours = ("red", "green", "blue")
empty = ()
singleton = (5,) # tuple with a single element
Note: Tuples can contain heterogeneous elements and even other tuples.
Accessing elements
Just like lists, indices are used (starting from 0).
t = ("a", "b", "c", "d")
print(t[0]) # a
print(t[2]) # c
print(t[-1]) # d (last element)
Immutability
Once created, a tuple cannot be modified: you cannot add, delete or change elements. This makes it “safer” when you don’t want data to be altered.
t = (1, 2, 3)
# t[0] = 99 # ERROR: tuple objects do not support item assignment
Note: You can however create a new tuple from existing ones:
t = (1, 2, 3) new = t + (4, 5) print(new) # (1, 2, 3, 4, 5)
Multiple assignments
Tuples are widely used for unpacking and multiple assignments.
point = (3, 4)
x, y = point
print(x, y) # 3 4
a, b, c = (10, 20, 30)
print(a+b+c) # 60
Tuples as dictionary keys
Because they are immutable, tuples can be used as keys in a dictionary (which is not possible with lists).
contacts = {
("Mario", "Rossi"): "333-1234567",
("Luca", "Bianchi"): "333-7654321"
}
print(contacts[("Mario", "Rossi")])
Useful functions
len(t)→ length of the tuple.min(t),max(t)→ minimum and maximum (if comparable).tuple(list)→ converts a list to a tuple.- slicing → works like with lists:
t[1:3].
t = (10, 20, 30, 40)
print(len(t)) # 4
print(t[1:3]) # (20, 30)
print(tuple([1, 2, 3])) # (1, 2, 3)
Differences from lists and sets
- Lists: ordered, mutable, allow duplicates.
- Sets: unordered, mutable, eliminate duplicates, not indexable.
- Tuples: ordered, immutable, allow duplicates, indexable.
lst = [1, 2, 2, 3]
s = {1, 2, 2, 3}
tup = (1, 2, 2, 3)
print(lst) # [1, 2, 2, 3]
print(s) # {1, 2, 3}
print(tup) # (1, 2, 2, 3)
In brief: use a tuple when you need an ordered, immutable collection of values — useful for representing coordinates, dates or fixed records.
EC