Learn Python Programming  /  Data Structures  /  Tuple

Tuple

A tuple is just like a list โ€” an ordered collection of items โ€” except it cannot be changed after creation. That immutability is the entire point of a tuple.

Creating a Tuple

R Code
point = (4, 7)
colours = ("red", "green", "blue")
single = (5,)   # the trailing comma is required for a one-item tuple

print(point)
print(type(single))
Output
(4, 7)
<class 'tuple'>
⚠ Common Mistake
(5) is just the integer 5 in parentheses, not a tuple - the trailing comma (5,) is what actually makes it a tuple. This one catches almost everyone the first time.

Indexing and Slicing Work Just Like Lists

R Code
colours = ("red", "green", "blue")

print(colours[0])
print(colours[-1])
print(colours[0:2])
Output
red
blue
('red', 'green')

Tuples Are Immutable

R Code
point = (4, 7)
point[0] = 10   # this line raises an error
Output
Traceback (most recent call last):
  ...
TypeError: 'tuple' object does not support item assignment

Tuple Unpacking

One of the most useful tuple features: assign each element to its own variable in one line.

R Code
point = (4, 7)
x, y = point

print(x)
print(y)

# common pattern: a function returning multiple values as a tuple
def min_max(nums):
    return min(nums), max(nums)

low, high = min_max([4, 9, 2, 7])
print(low, high)
Output
4
7
2 9

Advanced: Why Choose a Tuple Over a List?

🚀 Advanced Example
Because tuples are immutable, they are hashable and can be used as dictionary keys - something a list can never do.
R Code
distances = {
    ("NYC", "LA"): 3944,
    ("NYC", "Chicago"): 1270
}

print(distances[("NYC", "LA")])
Output
3944

Key Points

  • A tuple is an ordered, immutable collection - once created, it cannot be changed.
  • A single-item tuple needs a trailing comma: (5,) not (5).
  • Tuple unpacking (x, y = point) is a clean way to assign multiple values at once.
  • Because tuples are immutable, they can be used as dictionary keys - lists cannot.