CodeBlanks Logo Icon CodeBlanks

namedtuple

Learn named tuples with namedtuple.

namedtuple

A namedtuple is immutable like a tuple but its fields can be accessed by name. It comes from the collections module; it is ideal for small, immutable data structures.

Example: Point = namedtuple("Point", ["x", "y"]). This produces a class; you create an instance with p = Point(3, 4). You access fields by name with p.x and p.y; or by index with p[0] and p[1]. It is immutable like a tuple; you cannot write p.x = 5.

When to use it?

namedtuple is ideal for small, immutable data sets. Example: a point, a coordinate, a color (RGB). When a dataclass would be too heavy and only a few fields are needed, namedtuple is lighter.

It is hashable like a tuple; it can be a dictionary key. len(p) gives the field count. With p._asdict() you can convert it to a dict. Memory usage is lower than a normal class.

Practice Define the Point namedtuple

Start with from collections import namedtuple. Produce a namedtuple with Point = namedtuple("Point", ["x", "y"]). Create an instance with p = Point(3, 4) and print with print(p.x, p.y).

Starter code

main.py
# Define the Point namedtuple

Sample solution

main.py
# Define the Point namedtuple
from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y)

Expected output

3 4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How does namedtuple allow access?

  • Only by index
  • Only by name
  • Both by name and index Correct answer
  • Only by method

Explanation: namedtuple supports both.

2 namedtuple definition

Question
from collections import namedtuple

Point = ____("Point", ["x", "y"])
p = Point(3, 4)
print(p.x)
Answer
from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x)

Explanation: The namedtuple function produces a new class.

3 Match the namedtuple parts

Term Meaning
namedtuple Function
Point Produced class
p.x Access by name
p[0] Access by index

All lessons in Intermediate