Back
+15 XP
Concept

`collections.namedtuple`: Lightweight Typed Tuples

`namedtuple('Name', ['fields'])` creates a tuple where values can be accessed by human field names (`pt.x`) with zero extra RAM overhead 🏷️.

python
from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20)
print(p.x, p.y)  # 10 20 (Readable like an object!) 🎯
print(p[0])      # 10 (Fast and unpackable like a tuple!)

# 29. `collections.namedtuple`: Lightweight Typed Tuples `namedtuple('Name', ['fields'])` creates a tuple where values can be accessed by human field names (`pt.x`) with zero extra RAM overhead 🏷️: ```python from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) p = Point(10, 20) print(p.x, p.y) # 10 20 (Readable like an object!) 🎯 print(p[0]) # 10 (Fast and unpackable like a tuple!) ``` Unlike full classes, `namedtuple` instances have no `__dict__` overhead. They are as lightweight as raw C structs in memory while making your code 100x cleaner to read. 🚀 --- ### Question Can you modify an attribute on a namedtuple like `p.x = 99`? 🔒 - [ ] a. No, namedtuples inherit tuple immutability and raise an `AttributeError` 🛡️ - [ ] b. Yes, namedtuples are fully mutable like dictionaries - [ ] c. Only if you convert it into a string first 🔤 - [ ] d. Yes, but the change only appears after restarting Python 🔄 --- ### Challenge Define a `namedtuple` called `Color` with fields `["r", "g", "b"]`. Instantiate `c = Color(255, 0, 0)` and print `c.r`. 🎯 <details> <summary>Solution</summary> ```python from collections import namedtuple Color = namedtuple("Color", ["r", "g", "b"]) c = Color(255, 0, 0) print(c.r) ``` </details>

Checkpoint

Can you modify an attribute on a namedtuple like `p.x = 99`? 🔒

Practice

Define a `namedtuple` called `Color` with fields `["r", "g", "b"]`. Instantiate `c = Color(255, 0, 0)` and print `c.r`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks