Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • define tuple and explain immutability
  • create tuples correctly
  • unpack tuple values into variables
  • compare tuple with list

What is a tuple?

  • A tuple is an ordered, immutable collection.
  • Immutable means values cannot be changed after creation.
Examples:
point = (2, 5)
days = ("Mon", "Tue", "Wed")

Single-element tuple trap

a = (5)
print(type(a))  # int
Correct single-element tuple:
a = (5,)
print(type(a))  # tuple

Indexing and slicing

t = (10, 20, 30, 40)
print(t[1])     # 20
print(t[1:3])   # (20, 30)

Immutability trap

t = (1, 2, 3)
# t[1] = 99   # TypeError

Packing and unpacking

student = ("Asha", 19, 88)
name, age, marks = student
print(name, age, marks)

Tuple vs list

  • tuple: fixed data, immutable
  • list: changeable data, mutable

Exam hints and traps

  • tuple uses ()
  • single-element tuple needs trailing comma
  • unpack variable count must match tuple length
  • tuple can store mixed types

Quick practice

  1. Create tuple of three cities.
  2. Unpack (7, 8) into a and b.
  3. Explain why tuple is preferred for fixed coordinate pair.