What are “named tuples” in Python?
A Tuple is a collection of objects separated by commas and enclosed within parentheses. It is similar to a list in terms of indexing, nested objects, repetition and a few other characteristics, but it is immutable, unlike mutable lists.
To know more about the differences between lists and tuples, refer to the article differences between lists and tuples
The named tuples are part of the collections module and are very similar to regular tuples. The main difference between them is that values stored in a named tuple can be accessed using field names instead of indexing.
from collections import namedtuple employee=namedtuple('employee', ('rollno, name, age')) e= employee(101, "Ram", 23) print(e.name) print(e.age) print(e.rollno)
One more advantage of using named tuples is that they allow setting default values using the defaults iterable argument which gets assigned when we don’t assign any of the values in the named tuple.
from collections import namedtuple employee=namedtuple('employee', ('rollno, name, age'), defaults=) e= employee(101, "Ram") print(e.name) print(e.age) print(e.rollno)
They also have the ability to rename duplicate or invalid fields automatically using the rename boolean argument.