Namedtuple in Python

We offer you a brighter future with FREE online courses - Start Now!!

The namedtuple in Python is a function available in the collections module. It returns a subclass a tuple. The elements in the returned tuple can be accessed using either labels or normal indexing.

Create Python namedtuple

To create a Python namedtuple, we need to first import the collections module. We can use the following line of code to import the collections module.

Example of importing the namedtuple in Python

from collections import namedtuple

We can create the namedtuple objects by using the imported class. To create a namedtuple object, we use the following syntax.

Syntax

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

Example of using namedtuple in Python

from collections import namedtuple
car = namedtuple('Car', ['Make', 'Model'])
my_car = car("Ford", "Figo")
print(my_car)

Output

Car(Make=’Ford’, Model=’Figo’)

In the above code example, we created a namedtuple by passing two arguments. The first argument ‘Car’ defines the name of the namedtuple and the second argument list contains several strings which define the names of labels.

We can also pass a string instead of a list as the second argument. For this, the names of the labels must be separated by space.

Example of using namedtuple in Python

from collections import namedtuple
study = namedtuple('Study', ['Topic', 'Website'])
my_work = study('Python', 'PythonGeeks')
print(my_work)

Output

Study(Topic=’Python’, Website=’PythonGeeks’)

In the above code example, we passed a string of labels separated by space.

Getting Elements from a namedtuple in Python

Python provides three different ways for accessing elements in a namedtuple.

Using Labels

We can access an element using a label and a dot operator.

Example of using namedtuple in Python

from collections import namedtuple
study = namedtuple('Study', ['Topic', 'Website'])
my_work = study('Python', 'PythonGeeks')
print(my_work.Topic)
print(my_work.Website)

Output

Python
PythonGeeks

Using Indexing in Python Namedtuple

We can access an element using normal indexing.

Example of using namedtuple in Python

from collections import namedtuple
study = namedtuple('Study', ['Topic', 'Website'])
my_work = study('Python', 'PythonGeeks')
print(my_work[0])
print(my_work[1])

Output

Python
PythonGeeks

Using getattr()

Python has the built-in function getattr() to access the elements of a namedtuple by using the following syntax.

Syntax

getattr(namedtuple, label)

Example of using namedtuple in Python

from collections import namedtuple
study = namedtuple('Study', ['Topic', 'Website'])
my_work = study('Python', 'PythonGeeks')
print(getattr(my_work, 'Topic'))
print(getattr(my_work, 'Website'))

Output

Python
PythonGeeks

Methods of the namedtuple Class in Python

Namedtuple has several useful methods that we can use.

1. _fields

This attribute returns a tuple containing the names of labels in the namedtuple. This is beneficial when we want to know what labels a namedtuple has.

Example of using _fields in Python

from collections import namedtuple
study = namedtuple('Study', ['Topic', 'Website'])
my_work = study('Python', 'PythonGeeks')
print(my_work._fields)

Output

(‘Topic’, ‘Website’)

2. _replace(**kwargs)

We need to pass the label name and its new value to this method. It replaces the previous value with the new value. This comes handy when we want to modify a namedtuple.

Example of using _replace() in Python

from collections import namedtuple
study = namedtuple('Study', ['Topic', 'Website'])
my_work = study('Python', 'PythonGeeks')
print(my_work)
my_work = my_work._replace(Topic="Java")
print(my_work)

Output

Study(Topic=’Python’, Website=’PythonGeeks’)
Study(Topic=’Java’, Website=’PythonGeeks’)

3. _make(iterable)

The method takes an iterable and converts it into a namedtuple. The number of elements in the iterable must be equal to the number of labels in the namedtuple. Otherwise, it raises a TypeError.

Example of using _make() in Python

from collections import namedtuple
study = namedtuple('Study', ['Topic', 'Website'])
my_work = study._make(['Python', 'PythonGeeks'])
print(my_work)

Output

Study(Topic=’Python’, Website=’PythonGeeks’)

4. _asdict()

This method creates a dictionary from a namedtuple.

Example of using _asdict() in Python

 

from collections import namedtuple
study = namedtuple('Study', ['Topic', 'Website'])
my_work = study('Python', 'PythonGeeks')
print(my_work)
my_dict = my_work._asdict()
print(my_dict)

Output

Study(Topic=’Python’, Website=’PythonGeeks’)
{‘Topic’: ‘Python’, ‘Website’: ‘PythonGeeks’}

Converting Dictionary to namedtuple

To convert a dictionary to namedtuple, we use the double-star-operator ‘**’.

Example of using double-star-operator in Python

from collections import namedtuple
study = namedtuple('Study', ['Topic', 'Website'])
my_dict = {'Topic': 'Python', 'Website': 'PythonGeeks'}
print(my_dict)
my_work = study(**my_dict)
print(my_work)

Output

{‘Topic’: ‘Python’, ‘Website’: ‘PythonGeeks’}
Study(Topic=’Python’, Website=’PythonGeeks’)

Advantages of Python namedtuples

  • The main advantage of the namedtuple is the ability of accessing its elements through labels. This allows us to use a tuple like a dictionary.
  • These are immutable whereas dictionaries are mutable.
  • These are ordered whereas dictionaries are unordered
  • They are more memory-efficient than typical dictionaries.

Interview Questions on Python namedtuple

Q1. Create a namedtuple called Car with labels Model and Make.

Ans 1. Complete code is as follows:

from collections import namedtuple
Car = namedtuple('Car', ['Make', 'Model'])
my_car = Car('Ford', 'Figo')
print(my_car)

Output

Car(Make=’Ford’, Model=’Figo’)

Q2. Create a namedtuple Car with labels Model and Make and print only the Model of it without using indexing.

Ans 2. Complete code is as follows:

from collections import namedtuple
Car = namedtuple('Car', ['Make', 'Model'])
my_car = Car('Ford', 'Figo')
print(my_car.Model)

Output

Figo

3. Create a namedtuple Car with labels Model and Make and print only the Model of it without using indexing and labels.

Ans 3. Complete code is as follows:

from collections import namedtuple
Car = namedtuple('Car', ['Make', 'Model'])
my_car = Car('Ford', 'Figo')
print(getattr(my_car, 'Model'))

Output

Figo

Q4. Write a program to convert the iterable [“Apple”, “iphone”, 11, “128gb”, “Green”] into a namedtuple with appropriate labels.

Ans 4. Complete code is as follows:

from collections import namedtuple
iterable = ["Apple", "iphone", 11, "128gb", "Green"]
phone = namedtuple('phone', ['Company', 'Name', "Model", "Storage", "Color"])
my_phone = phone._make(iterable)
print(my_phone)

Output

phone(Company=’Apple’, Name=’iphone’, Model=11, Storage=’128gb’, Color=’Green’)

Q5. Write a program to convert the dictionary {“Name”: “John”, “Age”: 24} into a namedtuple. Print the namedtuple and the names of its labels.

Ans 5. Complete code is as follows:

from collections import namedtuple
dictionary = {"Name": "John", "Age": 24}
person = namedtuple("person", "Name Age")
john = person(**dictionary)
print(john)
print(john._fields)

Output

person(Name=’John’, Age=24)
(‘Name’, ‘Age’)

Conclusion

We learnt about the namedtuple and how it differs from a regular tuple in this article. We also learnt about a number of handy namedtuple methods. The namedtuple’s benefits were finally discussed. Please feel free to ask any queries you may have in the comments area.

Did you like our efforts? If Yes, please give PythonGeeks 5 Stars on Google | Facebook

Leave a Reply

Your email address will not be published. Required fields are marked *