Python Tuples
A tuple is an ordered collection, like a list, but it is immutable: once created, it can't be changed. Tuples are written with parentheses (or just commas).
point = (3, 4)
rgb = (255, 128, 0)
person = ("Minh", 29, "Da Nang")
print(point, rgb, person)
print(type(point).__name__, len(person))(3, 4) (255, 128, 0) ('Minh', 29, 'Da Nang')
tuple 3
Lists vs tuples
| List | Tuple | |
|---|---|---|
| Syntax | [1, 2] |
(1, 2) |
| Mutable | yes | no |
| Typical use | many items of the same kind | a fixed group of related values (a record) |
| Can be a dict key | no | yes (if its items are hashable) |
| Methods | many | only count() and index() |
A good rule of thumb: a list is a collection (e.g. all temperatures this week), a tuple is a record (e.g. one (latitude, longitude) pair).
Creating tuples
It's the comma that makes a tuple, not the parentheses. That's why a one-item tuple needs a trailing comma:
a = 1, 2, 3 # parentheses are optional
b = ("solo",) # one-item tuple
c = ("solo") # just a string in parentheses!
d = () # empty tuple
e = tuple([7, 8]) # from another iterable
print(a, b, c, d, e)
print(type(b).__name__, type(c).__name__)(1, 2, 3) ('solo',) solo () (7, 8)
tuple str
Accessing items
Indexing, slicing, in, len and loops all work just as with lists:
week = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
print(week[0], week[-1])
print(week[5:])
print("Wed" in week)
print(week.index("Thu"), week.count("Mon"))Mon Sun
('Sat', 'Sun')
True
3 1
Tuples can't be changed
size = (1920, 1080)
try:
size[0] = 2560
except TypeError as err:
print("Error:", err)
# To "change" a tuple, build a new one
size = (2560,) + size[1:]
print(size)Error: 'tuple' object does not support item assignment
(2560, 1080)
Note: The tuple itself is immutable, but if it contains a mutable object such as a list, that list can still change:
t = ([1],); t[0].append(2)works.
Unpacking
Tuples are most often used through unpacking — assigning their items to separate names in one step:
location = ("Hue", 16.46, 107.59)
city, lat, lon = location
print(city, lat, lon)
first, *middle, last = (1, 2, 3, 4, 5)
print(first, middle, last)
for name, score in [("Lan", 9), ("Phuc", 7)]:
print(name, "scored", score)Hue 16.46 107.59
1 [2, 3, 4] 5
Lan scored 9
Phuc scored 7
Returning several values from a function
A function that "returns several values" is really returning one tuple, which the caller unpacks:
def min_max(values):
return min(values), max(values)
low, high = min_max([4, 9, 1, 7])
print(low, high)
print(min_max([5, 3]))1 9
(3, 5)
Named tuples
When a tuple has more than two or three fields, positions like p[2] become hard to read. collections.namedtuple lets you name the fields while keeping all the tuple behaviour:
from collections import namedtuple
Book = namedtuple("Book", ["title", "author", "year"])
b = Book("Dune", "Frank Herbert", 1965)
print(b.title, "-", b.year)
print(b[1])
print(b)Dune - 1965
Frank Herbert
Book(title='Dune', author='Frank Herbert', year=1965)
Test yourself
Which of these creates a tuple with one item?
- (5)
- (5,)
- [5]
- tuple(5)
Why can a tuple be used as a dictionary key but a list cannot?
- Tuples are faster
- Tuples are immutable and hashable
- Lists are too big
- Dictionaries only accept tuples