Tuples

Tuples are ordered collections that cannot be changed.

Syntaxpoint = (3, 4) x, y = point

A 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

Example · python
point = (3, 4)
print(point[0])

x, y = point
print(x, y)

# point[0] = 9 would raise a TypeError

# Output:
# 3
# 3 4

When 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.

Example · python
coordinates = (51.5074, -0.1278)
print(coordinates[0])   # 51.5074
print(coordinates[1])   # -0.1278
print(len(coordinates)) # 2

Unpack a tuple

Unpacks a three-element tuple into three named variables in a single assignment.

Example · python
rgb = (255, 128, 0)
red, green, blue = rgb
print(f'R={red} G={green} B={blue}')

# Output:
# R=255 G=128 B=0

Tuple as immutable record

Uses a tuple as a fixed set of constants; 'in' checks membership without risk of mutation.

Example · python
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

  • Be the first to comment on this lesson.