Python Tuples
tuple_name = (item1, item2, item3)
tuple_name[index]
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]) # index like a list
print(point[1:3]) # slice like a list, returns a tuple
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 # unpacks the tuple's values into x and y
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) # concatenates into a new tuple
print(a * 2) # repeats a's elements into a new tuple
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)) # how many times 2 appears
print(t.index(3)) # position of the first 3
- Writing a one-item tuple as
(5), which is just the integer 5; a one-item tuple needs a trailing comma,(5,). - Trying to change an item with
t[0] = 1, which raisesTypeErrorbecause tuples are immutable. - Unpacking with the wrong number of names, as in
a, b = (1, 2, 3), which raisesValueError: too many values to unpack.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: