Python Tuples
What is a Tuple?
A tuple is an ordered collection like a list, but once created its elements can't be reassigned, added, or removed -- that immutability makes tuples usable as dictionary keys and signals to readers that the data shouldn't change, like coordinates (x, y).
Example: What is a Tuple?
point = (3, 4)
print(point)
Accessing Tuple Items
Tuples support the exact same square-bracket indexing and slicing as lists, so my_tuple[0] and my_tuple[1:3] work identically -- the only real difference is you can't assign through them afterward.
Example: Accessing Tuple Items
point = (3, 4, 5)
print(point[0])
print(point[1:3])
Tuple Unpacking
Unpacking lets you write x, y = point to pull a tuple's values into named variables in one line, which is why functions that return multiple values (like divmod()) return them as a tuple you can immediately destructure.
Example: Tuple Unpacking
point = (3, 4)
x, y = point
print(x, y)
Tuple Operations
You can't modify a tuple in place, but + concatenates two tuples into a brand-new one and * repeats a tuple's elements, both producing fresh tuple objects rather than touching the originals.
Example: Tuple Operations
a = (1, 2)
b = (3, 4)
print(a + b)
print(a * 2)
Tuple Methods
Because tuples can't grow or shrink, they only need count(value) (how many times a value appears) and index(value) (its first position) -- there's no append or remove to support.
Example: Tuple Methods
t = (1, 2, 2, 3)
print(t.count(2))
print(t.index(3))
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: