Sub topic 1
Python Tuples and Unpacking
What a tuple is and when to use one
Assume you know basic variables, lists, indexing, functions, and for loops.
A tuple is an ordered sequence of values. Like a list, it can contain different types and supports indexing. Unlike a list, a tuple cannot be changed after creation.
Use a tuple for a fixed group of related values, such as coordinates, dimensions, or a database record.
point = (3, 4)
print(point[0])
print(len(point))Prerequisites
You should understand variables, lists, zero-based indexing, function calls, and for loops.
Creating tuples, and why the comma matters
Parentheses can make a tuple easier to read, but the comma creates the tuple. This matters especially for a one-element tuple.
point = (3, 4)
single = (3,)
not_a_tuple = (3)
no_parentheses = 1, 2, 3
print(type(point))
print(type(single))
print(type(not_a_tuple))
print(no_parentheses)(3,) is a tuple. (3) is just the integer 3. Python also permits tuple creation without parentheses when commas make the grouping clear.
Indexing, slicing and common operations
Tuple indexing and slicing work like list indexing. A slice creates another tuple. You can also concatenate tuples with + and repeat them with *.
letters = ("a", "b", "c", "d")
print(letters[1])
print(letters[-1])
print(letters[1:3])
print(letters + ("e",))
print(("x",) * 3)
print("c" in letters)These operations create new tuples rather than modifying letters.
Immutability: what is fixed and what is not
Tuple immutability means that the tuple's item references cannot be replaced, added, or removed.
record = (["Ada"], 42)
record[0].append("Grace")
print(record)
try:
record[1] = 43
except TypeError as error:
print(error)The list inside record is mutable, so its contents can change. The tuple still points to the same list. Immutability protects the tuple structure, not every object stored inside it.
Exercise
What does (7) represent, and what does (7,) represent?
Show answer
(7) is an integer. (7,) is a one-element tuple.