Named Tuples

Creating tuples with named fields

Interview Relevant: Advanced usage

Named Tuples

Tuples with named fields for readability.

Code Examples

Named tuples for structured data.

python
1from collections import namedtuple
2
3# Define named tuple
4Point = namedtuple('Point', ['x', 'y'])
5Person = namedtuple('Person', 'name age city')
6
7# Create instances
8p = Point(3, 4)
9person = Person('Alice', 25, 'NYC')
10
11# Access by name
12p.x       # 3
13p.y       # 4
14person.name  # 'Alice'
15
16# Still a tuple
17p[0]      # 3
18len(p)    # 2
19
20# Convert to dict
21p._asdict()  # {'x': 3, 'y': 4}
22
23# Create new with replaced values
24p2 = p._replace(x=10)  # Point(x=10, y=4)
25
26# Default values (Python 3.7+)
27Point = namedtuple('Point', ['x', 'y'], defaults=[0, 0])

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In