Standard tuple uses numerical indexes to access its members. Remembering index for each value can lead to errors, especially if the tuple has a lot of fields. A namedtuple in Python assigns names, as well as the numerical index, to each member. It allow for more readable, self-documenting code. They can be used wherever regular tuples are used.

Syntax

Python namedtuple is an immutable container type. To use this, import the module collections.namedtuple. Syntax for creating named tuple is

collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)

It returns a new tuple subclass named typename, where

  • typename : Tuple subclass named typename. Fields of new subclass is accessible by attribute lookup as well as being indexable and iterable.
  • field_names : Sequence of strings such as [‘x’, ‘y’]. Alternatively, it can be a single string with each fieldname separated by whitespace and/or commas, for example ‘x y’ or ‘x, y’.
  • rename : If true, invalid fieldnames are automatically replaced with positional names.
  • defaults : An iterable of default values. They are applied to the rightmost parameters. For example, if the fieldnames are [‘x’, ‘y’, ‘z’] and the defaults are (1, 2), then x will be a required argument, y will default to 1, and z will default to 2.
  • module : If defined, the module attribute of the named tuple is set to that value.

Important Methods

In addition to the methods inherited from tuples, named tuples support additional methods and attributes. Additional method and attribute names start with an underscore.

  • _asdict() : Return a new dict which maps field names to their corresponding values.
  • _replace(**kwargs) : Return a new instance of the named tuple replacing specified fields with new values.
  • _fields : Tuple of strings listing the field names.

Following example illustrates the use of above methods and attributes.

# Demonstrate the usage of namdtuple objects
import collections

# Create a Point namedtuple
Point = collections.namedtuple("Point", "x y")

p = Point(10, 20)

print(p)
# Output
# Point(x=10, y=20)

# Access using field
print(p.x, p.y)
# Output
# 10 20

# Create a new instance using _replace 
p = p._replace(x=100)
print(p)
# Output
# Point(x=100, y=20)

# Convert to Dict()
print(p._asdict())
# Output
# OrderedDict([('x', 100), ('y', 20)])

# Get the filed name
print(p._fields)
# Output
# ('x', 'y')

Example

In the below example, Person named tuple is created having field name, age and gender. Field values are access using positional index and filed names. When rename field is true, invalid field name (reserved keyword class) is replaced by positional name.

import collections

# Create a named tuple subclass Person
Person = collections.namedtuple('Person', 'name age gender')

print('Type of Person : ', type(Person))
# Output
# Type of Person :  <class 'type'>

# Create new person object
p = Person(name='Bob', age=30, gender='male')
print(p)

# Output
# Person(name='Bob', age=30, gender='male')

# Field by name
print('Field by name:', p.name)
# Output
# Field by name: Bob

# Fields by index
print ('{} is a {} year old {}'.format(p.name, p.age, p.gender))
# Output
# Bob is a 30 year old male

# Person with reserved keyword 'class'
Person = collections.namedtuple('Person', 'name class age gender', rename=True)
print(Person._fields)
# Output
# ('name', '_1', 'age', 'gender')