Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • use tuple methods and nested tuples
  • perform tuple unpacking cleanly
  • explain tuple use in safe fixed records

Tuple methods

Tuples have fewer methods than lists because they are immutable.
t = (1, 2, 2, 3, 2)
print(t.count(2))  # 3
print(t.index(3))  # 3

Swapping values with tuples

a, b = 10, 20
a, b = b, a
print(a, b)  # 20 10

Nested tuples

data = ((1, 2), (3, 4), (5, 6))
print(data[1])      # (3, 4)
print(data[1][0])   # 3

Tuple in dictionary keys / set elements

Because tuples are immutable, they are often used where mutable lists cannot be used.
d = {(1, 2): "point A"}
print(d[(1, 2)])

Tuple from iterable

letters = tuple("code")
print(letters)  # ('c', 'o', 'd', 'e')

Exam hints and traps

  • tuple methods are mainly count and index
  • tuple unpacking is common in MCQs
  • tuple can contain mutable items, but tuple structure itself stays fixed
Example:
t = ([1, 2], [3, 4])
t[0].append(9)
print(t)  # ([1, 2, 9], [3, 4])

Quick practice

  1. Swap x = 5, y = 9 without third variable.
  2. Count how many times 4 occurs in (4, 1, 4, 4, 2).
  3. Explain why tuple can be a dict key but list cannot.