Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 04 / Topic 2 of 11

Tuple

A tuple is an ordered, unchangeable (immutable) collection. Use round brackets (). Once made, you cannot add, remove or change items. Think of it as a printed train ticket: the details are fixed. Use it for fixed records, like a GPS point or a date.

Real-world example: the location of a shop, a person's record, and the lowest and highest marks.

shop = (28.6139, 77.2090)          # (latitude, longitude) of a shop in Delhi
print(shop[0])                     # 28.6139

# shop[0] = 10 -> TypeError: 'tuple' object does not support item assignment

# Packing and unpacking
person = "Asha", 21, "Pune"        # packing (brackets are optional)
name, age, city = person           # unpacking
print(f"{name} is {age}, lives in {city}")  # Asha is 21, lives in Pune

# Swap two values in one line
a, b = 5, 9
a, b = b, a
print(a, b)                        # 9 5

# Star unpacking: collect "the rest"
first, *rest = [90, 85, 70, 60]
print(first, rest)                 # 90 [85, 70, 60]
top, *middle, last = [90, 85, 70, 60]
print(top, middle, last)           # 90 [85, 70] 60

# Pack two results into a tuple, then unpack them
marks = [67, 92, 45, 88]
low, high = min(marks), max(marks)
print(low, high)                   # 45 92

single = ("only",)                 # one-item tuple needs a comma
print(type(single))                # <class 'tuple'>

Comparing tuples: Python compares the first items. Only if they are equal does it look at the next items, and so on. This is how a list of (total, name) tuples gets sorted by total, then by name.

print((186, "Meena") < (198, "Ravi"))   # True   (186 < 198, names not checked)
print((186, "Meena") < (186, "Asha"))   # False  (totals equal, so "Meena" vs "Asha")
scores = [(198, "Ravi"), (186, "Meena"), (186, "Asha")]
print(sorted(scores))   # [(186, 'Asha'), (186, 'Meena'), (198, 'Ravi')]

๐Ÿ” Going deeper: the comma makes a tuple, not the brackets: x = 1, 2 is already a tuple. In Part 5 you will see that a function "returning two values" is really returning one tuple. A tuple is fixed, but if it holds a list, that inner list can still change.

Done here? The practice set for Part 4 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide