ExampleEdit & Run

How to use namedtuples

#import the namedtuple factory method
from collections import namedtuple

#create a namedtuple to represent a Point
Point = namedtuple('Point', ['x', 'y'])

#Create objects from the namedtuple 'Point' 
p = Point(3, 4)

#Access the elements using the numeric indices
print(p[0], p[1])

#Access the elements using their names
print(p.x, p.y)
copy
Output:
3 4 3 4 [Finished in 0.012933656573295593s]

A namedtuple defined in the collections module is a type of sequence which is similar to a regular tuple but with some extra features. This data type makes it possible  to assign names to each position of the tuple as well as to access values by names rather than just their numeric indices.

Compared to the regular tuples, namedtuples are easier to read and work with, as they allow for more meaningful variable and attribute names. They also use less memory than dictionaries, as they are stored as a single object rather than a collection of key-value pairs.

Similarly to regular tuples, namedtuples are also immutable meaning that they cannot be modified once created.

Instantiating namedtuples

To create namedtuples we start by defining the structure of the tuple using the namedtuple factory method. This is where we declare the fields that objects of the namedtuple will contain.We achieve this using the following syntax:

Syntax:
namedtuple('tupleName', ['field1', 'field2', 'field3', ...]) 
copy

The tupleName  is the name of the namedtuple. The rest of the parameters are strings in an iterable object representing the names of the fields of the namedtuple. 

After the structure of the tuple has been established, we then create new objects by assigning a value to each field. 

ExampleEdit & Run

instantiating named tuples

from collections import namedtuple

Person = namedtuple('person', ['name', 'age', 'height'])

p1 = Person('John', 20, 175)

print(p1[0], p1.age, p1.height)
copy
Output:
John 20 175 [Finished in 0.012169958092272282s]

Accessing elements of a namedtuple object 

As we have seen from previous examples we can access an element in a namedtuple through its index or its field name. This is achieved using the dot notation in the case of field names and  the square brackets when using  index notation.

ExampleEdit & Run

Access the elements in a namedtuple using field names

from collections import namedtuple 

Person = namedtuple('Person', ['first_name', 'last_name', 'age']) 

p1 = Person('John', 'Smith', 30)

# Access elements 
print(p1.first_name)
print(p1.last_name)
print(p1.age)
copy
Output:
John Smith 30 [Finished in 0.012058580294251442s]
ExampleEdit & Run

Access the elements in a namedtuple using index notation

from collections import namedtuple 

Person = namedtuple('Person', ['first_name', 'last_name', 'age']) 

p1 = Person('Jane', 'Doe', 30)

# Access elements 
print(p1[0])
print(p1[1])
print(p1[2])
copy
Output:
Jane Doe 30 [Finished in 0.011512740515172482s]

Operations on namedtuples

Just like in regular tuples, we can perform various arithmetic operations on namedtuples including concatenation and repetition. However, most of these operations will result in a new regular tuple rather than a namedtuple object.

Concatenation

Concatenation is when you combine two namedtuples together. This operation results in a new regular tuple with the combined elements of the two namedtuples.

We use the plus(+) for concatenation.

ExampleEdit & Run

concatenation operation on namedtuples

from collections import namedtuple 

Car = namedtuple('Car', 'brand name color') 

car1 = Car('Ford', 'Fiesta', 'Blue') 

car2 = Car('Honda', 'Accord', 'Red') 

#Concatenate two cars 
cars = car1 + car2 

print(cars)
copy
Output:
('Ford', 'Fiesta', 'Blue', 'Honda', 'Accord', 'Red') [Finished in 0.012094100937247276s]

Repetition 

Repetition  is repeating the elements of a given namedtuple for a specified number of times. The operation results in a new regular tuple with the elements of the namedtuple repeated the number of times specified by the integer operand. We perform this operation using the asterisk(*) operator

ExampleEdit & Run

repetition operation on namedtuples

#import the namedtuple factory method
from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])

p = Point(0, 0)

print(p * 3)
copy
Output:
(0, 0, 0, 0, 0, 0) [Finished in 0.011831054463982582s]

Create a namedtuple from a dict

We can use the double unpacking operator(**) to create a namedtuple object from dictionary items

ExampleEdit & Run

Create a namedtuple object from a dictionary

from collections import namedtuple 

d = {'name': 'John Doe', 'age': 42, 'country': 'Netherlands'} 

Person = namedtuple('Person', d.keys()) 

p = Person(**d) 
print(p)

print(p.name, p.age, p.country)
copy
Output:
Person(name='John Doe', age=42, country='Netherlands') John Doe 42 Netherlands [Finished in 0.012189340777695179s]

namedtuple methods and attribute  

The namedtuple class  provide some methods that we can use to  further manipulate namedtuple objects.

The methods and attributes can be summarized as shown below.

method usage
_asdict() Returns a copy of the namedtuple in the form of a new dict object
_make(iterable) Creates a new instance of the namedtuple with the values of an iterable given as an argument.
_replace(**kwrgs) Replaces the fields of an existing instance of a namedtuple with the new values provided
_fiealds A tuple containing the field names of the namedtuple

Get the field names

ExampleEdit & Run

The _fields attribute

#import the namedtuple factory method
from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])

p = Point(0, 0)

print(p._fields)
copy
Output:
('x', 'y') [Finished in 0.011831285431981087s]

create a dictionary from a named tuple

ExampleEdit & Run

The _asdict() method

#import the namedtuple factory method
from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])

p = Point(0, 0)

d = p._asdict()

print(p)
print(d)
copy
Output:
Point(x=0, y=0) {'x': 0, 'y': 0} [Finished in 0.011941774748265743s]

Make a named tuple from an iterable

ExampleEdit & Run

The _make() method

from collections import namedtuple 

Person = namedtuple('Person', ['name', 'age', 'country']) 
data = ('Jane', 28, 'Canada')

p = Person._make(data)

print(p.name, p.age, p.country)
copy
Output:
Jane 28 Canada [Finished in 0.011403022333979607s]

Replace the values of a namedtuple

ExampleEdit & Run

The _replace() method 

from collections import namedtuple 

Person = namedtuple('Person', ['name', 'age', 'country']) 
data = ('Jane', 28, 'Canada')

p = Person._make(data)

print('old: ', p.name, p.age, p.country)

p = p._replace(name = 'Mary',age =  25, country = 'Finland')

print('new: ', p.name, p.age, p.country)
copy
Output:
old:  Jane 28 Canada new:  Mary 25 Finland [Finished in 0.012181802652776241s]