Named tuple is a more readable alternative to standard tuples (python
tuple built-in structure), which allows to describe the whole tuple.
Named tuples were introduced in Python 2.6. It was quite a long time ago, but they're still not very popular.
Tuples are imported from collections module:
You define a new data type, which is just a tuple subclass:
>>> from collections import namedtuple
In this example, our tuples will define Human data with 3 attributes: firstname, lastname and occupation. Now we may use our tuple subclass to instantiate a named tuple:
>>> Human = namedtuple('Human', ['firstname', 'lastname', 'occupation'])
As you can see, above provides more information than the standard tuple:
>>> john= Human('John', 'Lennon', 'musician') >>> john Human(firstname='John', lastname='Lennon', occupation='musician')
and this is the most important thing in named tuples.
('John', 'Lennon', 'musician')
Just to make clear, named tuples inherit behavior from standard tuples. They provide index access:
They are immutable:
>>> john 'John'
just like standard tuples:
>>> john = 'Paul' Traceback (most recent call last): File "
", line 1, in TypeError: 'Human' object does not support item assignment
and they can be iterated just like standard tuples:
>>> tup = (1,2,3) >>> tup = 'new value' Traceback (most recent call last): File "
", line 1, in TypeError: 'tuple' object does not support item assignment
and so on.
>>> for el in john: ... print el ... John Lennon musician
Important to mention the docs:
Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.don't worry that named tuples will use more memory than stadard tuples. A dictionary is created only for the tuple subclass (
Humanin above example).