Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python3
namedtuple
communitycreator

What is namedtuple in Python?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

What’s a namedtuple?

namedtuple is a subclass of tuple, which is used to create tuple-like objects with named fields and fixed length.

How to create namedtuples

There are 3 parameters used while creating a namedtuple.

  1. typename - indicates the name of namedtuple
  2. field_names - indicates the attributes associated with the namedtuple
  3. defaults - indicates the default values of the fields

There are 2 ways to create a namedtuple:

  1. Using typing module
from typing import NamedTuple

class Address(NamedTuple):
    street: str
    door_no: int
    country: str
  1. Using collections module
from collections import namedtuple
Address = namedtuple('Address', ['street', 'door_no', 'country'], defaults = ['Wall Street', '5', 'USA'])
new_address = Address()
print(new_address)

Different ways of access field names of a namedtuple

As namedtuples are a subclass of tuples, the fields can be accessed via the index or by the name of the field. The index value of a field is tied to the order during the declaration of the namedtuple.

Consider the above Address example. You can access the street field by name or by using 0 as the index value.

print(new_address[0])
# OR
print(new_address.street)

Converting list/dict to namedtuple

Consider a list containing the street, door number, and country. The _make() method can be used to convert the list to a namedtuple.

from collections import namedtuple
Address = namedtuple('Address', ['street', 'door_no', 'country'])
address_list = ['List Avenue', '23', 'USA']
new_address_list = Address._make(address_list)
print(new_address_list)
address_dict = {'street':'Dict Avenue', 'door_no': '32', 'country':'USA'}
new_address_dict = Address._make(address_dict.values())
print(new_address_dict)

Other operations of namedtuple

Name Description
_fields To list the field names
_asdict() To convert namedtuple to dict
_field_defaults Default values of the fields
_replace() To replace a field value of a namedtuple
from collections import namedtuple
Address = namedtuple('Address', ['street', 'door_no', 'country'], defaults = ['Wall Street', '5', 'USA'])
new_address = Address("Penn Street", "56", "USA")
print("Field names:\n")
print(new_address._fields)
print("-" * 10)
print("Field Default Values:\n")
print(new_address._field_defaults)
print("-" * 10)
print("Tuple as dictionary:\n")
print(new_address._asdict())
print("-" * 10)
print("Replace:\n")
print(new_address._replace(street="Bourbon Street"))

RELATED TAGS

python3
namedtuple
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring