Tuples
Tuples are ordered collections that cannot be changed.
Syntax
point = (3, 4)
x, y = pointA tuple is like a list, but immutable — once created it cannot be changed. Write it with parentheses.
Why use tuples?
- They protect data that should never change, like coordinates.
- They are slightly faster than lists.
- They can be used as dictionary keys, which lists cannot.
You can unpack a tuple into separate variables in one line.
Example
point = (3, 4)
print(point[0])
x, y = point
print(x, y)
# point[0] = 9 would raise a TypeError
# Output:
# 3
# 3 4When to use it
- A GPS module returns a (latitude, longitude) tuple that the caller unpacks into two variables.
- A function returns multiple values as a tuple so the caller can choose to unpack or keep them grouped.
- A set of HTTP status codes is stored in a tuple to prevent accidental modification at runtime.
More examples
Create and access a tuple
Creates a two-element tuple for a geographic point and accesses each element by index.
coordinates = (51.5074, -0.1278)
print(coordinates[0]) # 51.5074
print(coordinates[1]) # -0.1278
print(len(coordinates)) # 2Unpack a tuple
Unpacks a three-element tuple into three named variables in a single assignment.
rgb = (255, 128, 0)
red, green, blue = rgb
print(f'R={red} G={green} B={blue}')
# Output:
# R=255 G=128 B=0Tuple as immutable record
Uses a tuple as a fixed set of constants; 'in' checks membership without risk of mutation.
ALLOWED_METHODS = ('GET', 'POST', 'PUT', 'DELETE')
method = 'PATCH'
if method not in ALLOWED_METHODS:
print(f'{method} is not allowed')
# Output:
# PATCH is not allowed
Discussion