Tuple
A tuple is similar to a list, but it is immutable (cannot be changed after creation). Tuples use parentheses ( ) and are faster than lists.
The immutability of tuples makes them safe to use for data that must not change while the program runs. For example, geographic coordinates, color constants, or fixed configurations. Because tuples cannot be changed, Python can allocate memory more efficiently, making tuple operations faster than lists.
Tuples are also commonly used for unpacking values. This allows you to swap two variables without a temporary variable, or to return multiple values from a function neatly. In addition, tuples can be used as dictionary keys because they are immutable — something lists cannot do.
Code Example
# Creating a tuple
coordinates = (10, 20)
color_rgb = (255, 128, 0)
single = (42,) # a 1-element tuple needs a comma
# Accessing elements
print(coordinates[0]) # 10
# Unpacking
x, y = coordinates
print(x, y) # 10 20
# Tuples in a for loop
data = [("A", 90), ("B", 85), ("C", 78)]
for name, score in data:
print(f"{name}: {score}")
Code Explanation
- Creating a tuple:
coordinates = (10, 20)creates a tuple with two elements.single = (42,)uses a trailing comma, because without the comma Python would treat it as a plain integer. - Accessing elements: Like lists, tuple elements are accessed with indices starting from 0.
coordinates[0]returns10. - Unpacking:
x, y = coordinatesunpacks the tuple's contents into separate variables. This is equivalent to writingx = coordinates[0]andy = coordinates[1]. - Tuples in a loop: Each item in the
datalist is a tuple(name, score). Withfor name, score in data, Python automatically performs unpacking on each iteration.
Everyday Example
A teacher wants to store a list of student grades in the format (name, subject, grade). This data will not change during a semester. The teacher can store it as tuples so the data is not accidentally modified.
score_list = [
("John", "Math", 90),
("Alice", "Physics", 85),
("Maria", "Chemistry", 92)
]
for name, subject, score in score_list:
print(f"{name} got {score} in {subject}")
# Output: John got 90 in Math
Summary
Tuples are a lightweight, fast data structure for storing fixed collections of values. Their immutability suits constant data and is safe to use as dictionary keys. Use tuples when you are sure the data does not need to change after creation.