← Back to Tutorials Chapter 6

Tuples

Tuple Basics

A tuple is an ordered, immutable collection enclosed in parentheses ():

point = (3, 4)
rgb = (255, 128, 0)
single = (1,)       # trailing comma required
empty = ()
coordinates = 10, 20  # parentheses optional

Immutability

Once created, a tuple cannot be changed:

t = (1, 2, 3)
# t[0] = 99  # TypeError!
# t.append(4)  # AttributeError!
# t.pop()  # AttributeError!

However, if a tuple contains mutable objects, those objects can be modified:

t = ([1, 2], [3, 4])
t[0].append(99)  # t is now ([1, 2, 99], [3, 4])

Accessing Elements

t = ("a", "b", "c", "d", "e")
t[0]      # "a"
t[-1]     # "e"
t[1:3]    # ("b", "c")
t[::-1]   # ("e", "d", "c", "b", "a")

Packing and Unpacking

# Packing
person = "Alice", 30, "Engineer"

# Unpacking
name, age, job = person
print(name)  # Alice
print(age)   # 30

# Extended unpacking (Python 3+)
first, *middle, last = (1, 2, 3, 4, 5)
print(first)   # 1
print(middle)  # [2, 3, 4]
print(last)    # 5

Nested Tuples

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

# Flatten a nested tuple
flat = tuple(item for row in nested for item in row)
print(flat)  # (1, 2, 3, 4, 5, 6)

namedtuple

The collections.namedtuple factory creates lightweight, immutable objects with named fields:

from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20)
print(p.x)       # 10
print(p.y)       # 20
print(p[0])      # 10 (indexing still works)

Person = namedtuple("Person", "name age job")
alice = Person("Alice", 30, "Engineer")
print(alice.name)  # Alice

Use ._replace() to create a new instance with modified fields:

alice2 = alice._replace(age=31)
print(alice2)  # Person(name='Alice', age=31, job='Engineer')

Tuple Methods

t = (1, 2, 3, 2, 4, 2)
t.count(2)  # 3
t.index(3)  # 2
# t.index(10)  # ValueError: tuple.index(x): x not in tuple

When to Use Tuples vs Lists

FeatureTupleList
MutableNoYes
Syntax()[]
HashableYes (if contents are)No
Use caseFixed data, dict keysDynamic collections
PerformanceSlightly fasterSlightly slower
Tip: Use tuples for data that should not change (e.g. coordinates, RGB values, database records). They are also commonly used to return multiple values from functions.
Python tuple diagram
Note: A tuple with one element requires a trailing comma — (1,) not (1). Without the comma, (1) is just the integer 1 in parentheses.

Practice Exercise

Create a namedtuple called Student with fields name, grade, and subjects (list of subject names). Create 3 students. Write a function that takes a tuple of students and returns the student with the highest grade. Print each student's details and the top student's info. Demonstrate packing, unpacking, and indexing.