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 lessonRead 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
- Create a NamedTuple for RGB ColorsBeginner
- Build a TypedDict for API ResponseBeginner
- Convert a Dict to a NamedTupleIntermediate
- Choose the Right ContainerAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz