Editor

Predict the Output: Immutability

Intermediate · Predict the output · from NamedTuple vs TypedDict vs Dataclass: Which to Choose?

From the lesson: NamedTuple vs TypedDict vs Dataclass: Which to Choose?

Python gives you three popular ways to bundle related data together: NamedTuple, TypedDict, and dataclass. Each one solves a slightly different problem.

Read the lesson

Read the code carefully. What will be printed? Remember: NamedTuples are immutable like regular tuples. The try/except block catches any errors.

from typing import NamedTuple
class Score(NamedTuple):
subject: str
points: int
s = Score('Math', 95)
try:
s.points = 100
print('Updated!')
except AttributeError:
print('Cannot modify!')
print(s.subject)

More NamedTuple and TypedDict exercises

All Python exercises · 50 practice problems · Object-Oriented Programming quiz