Tuples
Lists that can't change, and when that's useful.
🎬 Video version coming soon — read it now
A tuple is like a list that can't be changed once created. You write it with round brackets.
vizag = (17.6868, 83.2185) # latitude, longitude
rgb_blue = (0, 102, 204)
print(vizag[0]) # 17.6868Try vizag[0] = 18 and you get a TypeError. That's the point: the values are fixed.
Why would you want that?
- Safety: data that should never change (a GPS location, the days of the week) can't be changed by accident.
- Meaning: a tuple usually holds a fixed group of different facts about one thing, while a list holds many items of the same kind.
- Dictionary keys: tuples can be used as keys in dictionaries; lists can't. You'll see why in the dictionaries lesson.
Unpacking
Tuples shine when you pull values out into separate variables:
point = (17.6868, 83.2185)
lat, lon = point
print(f"Lat {lat}, Lon {lon}")This also gives Python's famous one-line swap:
a, b = 5, 9
a, b = b, a
print(a, b) # 9 5Returning several values
Functions (next course) often return a tuple:
marks = [78, 92, 65]
lowest, highest = min(marks), max(marks)One-item tuples
A single value needs a trailing comma, or Python treats the brackets as normal maths brackets:
t = (5,) # tuple
n = (5) # just the number 5Tip: Rule of thumb: a list of tuples is a great shape for simple records, like
[("Anil", 78), ("Bhavana", 92)].In one line
A tuple is an unchangeable group of values; use it for fixed records and unpack it with a, b = t.
Saved on this device. Sign in to keep progress everywhere.
Share with a friend