QA
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→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?