What Is a Tuple?
A tuple is an ordered, immutable collection. Once created, you cannot change, add, or remove elements.
point = (3, 4) rgb = (255, 128, 0) empty = () single = (7,) # trailing comma for single-element tuples
Accessing Elements
x, y = point # unpacking print(point[0])
When to Use a Tuple
- Fixed groups of related values (coordinates, RGB, database rows).
- Dictionary keys (lists cannot be keys โ tuples can).
- Returning multiple values from a function.
- Data that must not be modified accidentally.
Multiple Return Values
def min_max(nums):
return min(nums), max(nums) # returns a tuple
low, high = min_max([3, 1, 4, 1, 5])
Tuple Methods
t = (1, 2, 2, 3) print(t.count(2)) # 2 print(t.index(3)) # 3
Practise this on PyForm โ free
PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.
Open PyForm โ