Beginner LevelPython
What is collections.namedtuple and how does it compare to modern @dataclass definitions?
❓ Interview Prompt: Compare `collections.namedtuple` (lightweight immutable tuple subclass) vs `@dataclass` (Python 3.7+ class boilerplate generator).
1. 'collections.namedtuple':
•
Creates an immutable tuple subclass with named field access.
•
Lightweight, low memory, subscriptable by index ('p[0]') or attribute ('p.x').
2. '@dataclass' (Python 3.7+):
•
Generates standard Python classes with auto-generated '__init__', '__repr__', and '__eq__' methods based on type annotations.
•
Can be mutable or frozen ('@dataclass(frozen=True)').
Code Implementation Example
python
from collections import namedtuple
from dataclasses import dataclass
# 1. namedtuple: Immutable tuple subclass
PointNT = namedtuple('PointNT', ['x', 'y'])
p1 = PointNT(10, 20)
# 2. @dataclass: Class boilerplate generator
@dataclass
class PointDC:
x: float
y: float
p2 = PointDC(10.0, 20.0)💡Defining data records using namedtuple and @dataclass.
🎯 Interview Key Takeaway
Use @dataclass for modern type-annotated domain objects and namedtuple for lightweight immutable records.
#namedtuple#dataclasses#Data Structures#Beginner
Back to all Python Questions→