Tuples
In this tutorial, we'll store fixed ordered collections.
A tuple stores multiple values in order, like a list, but it cannot be changed after it is created.
point = (10, 20)
Tuples are useful for fixed groups of values, such as coordinates, RGB colours, or pairs.
Accessing Tuple Items
Tuples use indexes just like lists:
point = (10, 20)
print(point[0])
print(point[1])
Output:
10
20
Unpacking Tuples
Tuple unpacking lets you assign each value to a name:
point = (10, 20)
x, y = point
print(x)
print(y)
This is often clearer than using indexes again and again.
Tuples Cannot Be Changed
This gives an error:
point = (10, 20)
point[0] = 99
If you need to add, remove, or replace items, use a list instead.
One-Item Tuples
A one-item tuple needs a comma:
single = ("Python",)
Without the comma, Python treats it as just a value in parentheses.
Tuple or List?
Use a tuple when the values belong together as one fixed group:
birth_date = (2001, 5, 14)
Use a list when you expect the collection to grow or change:
shopping_list = ["bread", "milk"]
shopping_list.append("eggs")
If you are unsure, ask: "Will I need to add, remove, or replace items?" If yes, choose a list.
Practice
Create a tuple for a rectangle size, such as (width, height). Unpack it and calculate the area.