Implementing namedtuple
Using namedtuple
, a developer can give meaning to each item in a tuple and allow the tuple's fields to be accessed by name rather than by index value. This allows for more readable and better self-documenting code. Named tuples can be used in place of regular tuples with no adverse effects.
Named tuples can be thought of as using dictionary-type key:value
pairs, except in a tuple. It's not a true mapping of key to value, because named tuples are simply assigning a name to a sequence index position, that is, name=value, but it may help to conceptually think of them as unchanging mapped pairs. Named positions can be called by name or by position index.
namedtuple
is generated using the following command format:
collections.namedtuple(typename, field_names, *, verbose=False, rename=False, module=None)
The following is an explanation of the parts of the preceding command:
typename
: The name of the tuple subclass being created. Subclass instances automatically generatedocstrings...