Tuples
A tuple is an immutable ordered sequence. It can contain items of any type, including tuples themselves. Another sequence data structure is the list. Tuples and lists have some impoartant differences. Tuples are generally advised to be used for heterogenous (items of different types) and fixed-length data (RGB coordinates, or a database entry). For our purposes, however, it would be good to use tuples for any sequence work until you internalize working with immutable data structures.1
Creating tuples
a = (1, 2, 3)
b = 1, 2, 3 # parentheses optional; the comma makes the tuple
c = () # empty
d = (42,) # single item: trailing comma required
e = (42) # NOT a tuple, just the int 42
f = tuple([1, 2, 3]) # from any iterable
g = tuple("abc") # ('a', 'b', 'c')
Access and operations
t = (10, 20, 30, 40, 50)
t[0] # 10
t[-1] # 50
t[1:4] # (20, 30, 40)
t[::-1] # (50, 40, 30, 20, 10)
len(t) # 5
30 in t # True
t.count(20) # 1
t.index(30) # 2
(1, 2) + (3, 4) # (1, 2, 3, 4)
(1, 2) * 3 # (1, 2, 1, 2, 1, 2)
Tuples have only two methods: .count() and .index().
Immutability
rgb = (255, 128, 0)
rgb[0] = 100 # TypeError
del rgb[0] # TypeError
To “change” a tuple, you need to create a new one:
rgb = (255, 128, 0)
# "change" the red channel to 100
rgb = (100,) + rgb[1:] # (100, 128, 0)
Lists are mutable, so you can change items in place.
A tuple holding a mutable item, like (8, [1, 2]), still lets you modify the inner list.
a = (1,[1,3])
a # (1, [1, 3])
a[1][0]=6
a # (1, [6, 3])
Packing and unpacking
point = (3, 7)
x, y = point
first, *rest = (1, 2, 3, 4) # first=1, rest=[2, 3, 4]
a, *mid, z = (1, 2, 3, 4) # mid=[2, 3]
a, b = b, a # swap
def min_max(nums):
return min(nums), max(nums)
lo, hi = min_max([4, 9, 1])
-
Some parts of the following is produced by
Claude-sonnet-5.5. ↩