← Intro to programming with Python
Tuples: lists that never change
Group a few values that belong together.
A tuple is like a list that cannot be changed. You write it with round brackets: point = (3, 5). Why have one? Some groups of values belong together and should stay fixed, like a map location (latitude, longitude) or a date (day, month, year). Making them a tuple protects them from being changed by accident. You can also "unpack" a tuple into separate variables in one line.
home = (51.5, -0.12) # latitude, longitude
print(home[0]) # 51.5
lat, lon = home # unpacking
print(lat, lon)Indexing works just like lists. lat, lon = home puts the first value in lat and the second in lon.
Common mistake: trying to change a tuple, like home[0] = 40. That gives a TypeError, because tuples are fixed. Make a new tuple instead.
A neat trick: a, b = b, a swaps two variables using a tuple behind the scenes.