Tuples
Ordered but immutable — when you want a fixed collection you can't accidentally change.
A tuple looks like a list but is immutable — once created, it can't be changed, added to, or shrunk. Use one whenever a collection represents a fixed, unchanging group of values.
channel_info = ("CodeWithMunnaX", 2019, "YouTube")
print(channel_info[0]) # 'CodeWithMunnaX'
# channel_info[0] = "x" -- TypeError: 'tuple' object does not support item assignment
Tuple unpacking
This is where tuples shine — unpacking multiple values into named variables in one line, which is exactly how a function returns "multiple values" in Python (it's really returning one tuple).
name, founded, platform = channel_info
print(name, founded, platform)
def min_max(numbers):
return min(numbers), max(numbers) # returns a tuple
low, high = min_max([5, 3, 8, 1, 9])
print(low, high) # 1 9
Why prefer a tuple over a list?
- Intent — a tuple signals "this shouldn't change," which documents your code.
- Safety — you can't accidentally
.append()to it or mutate it from somewhere else. - Hashability — a tuple of immutable items can be used as a dict key or set element; a list can't.
locations = {
(28.6139, 77.2090): "Delhi",
(19.0760, 72.8777): "Mumbai",
}
print(locations[(28.6139, 77.2090)]) # 'Delhi'
A single-element tuple needs a trailing comma
not_a_tuple = (5) # this is just the int 5
a_tuple = (5,) # the comma makes it a tuple
print(type(not_a_tuple), type(a_tuple))Key points to remember
- •Tuples are ordered like lists but immutable — no append, remove, or item assignment after creation.
- •Unpacking (a, b, c = some_tuple) is the idiomatic way to pull a tuple's values into named variables.
- •A function 'returning multiple values' (return a, b) is really returning one tuple.
- •Because tuples are immutable, they're hashable and can be used as dict keys or set elements — lists can't.
- •(5) is just the int 5; (5,) — with a trailing comma — is a one-element tuple.
Unpacking and tuple-as-dict-key
Revision Flashcards
Tap a card to flip it and see the answer.