Named Tuples via typing.NamedTuple

Learn about the named tuples and how to implement them in Python.

Why do we need named tuples?

So, what do we do when we want to group values together but know we will frequently need to access them individually? There are actually several options, including these:

  • We can use an empty object instance. We can assign arbitrary attributes to this object. But without a good definition of what’s allowed and what types are expected, we’ll have trouble understanding this. And we’ll get a lot of mypy errors.

  • We can use a dictionary. This can work out nicely, and we can formalize the acceptable list of keys for the dictionary with typing.TypedDict hint.

  • We can use a @dataclass.

  • We can also provide names to the positions of a tuple. While we’re at it, we can also define methods for these named tuples, making them super helpful.

Named tuples are tuples with attitude. They are a great way to create an immutable grouping of data values. When we define a named tuple, we’re creating a subclass of typing.NamedTuple, based on a list of names and data types. We don’t need to write an __init__() method; it’s created for us.

Example

Here’s an example of the named tuple:

Get hands-on with 1200+ tech skills courses.