Python Namedtuple – Working and Benefits of Namedtuple in Python

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

In our journey so far, we have seen Python Tuple, which is an important container type. Today, we will talk about python namedtuple with its example & syntax.

Moreover, we will start our learning with a quick revision of Python tuple and Accessing Elements of python namedtuple. At last, we will cover the working, and benefits of python namedtuple.

So, let’s start the Python Namedtuple Tutorial.

Python Namedtuple - Working and Benefits of Namedtuple in Python

Python Namedtuple – Working and Benefits of Namedtuple in Python

What is Python Tuple?

Before we proceed, we think we must review tuples in python.
A python tuple is a container that can hold different values. Let’s take an example.

>>> colors=(255,0,0)

As you can see, we define it using parentheses. To access an element, we use indices. (And remember, indexing starts at 0)

>>> colors[0]

Output

255

What makes a >>> colors[0] python tuple unique is that its values cannot be changed, i.e., it is immutable.

Let’s try changing a value.

>>> colors[1]=10

Output

Traceback (most recent call last):File “<pyshell#316>”, line 1, in <module> c

olors[1]=10

TypeError: ‘tuple’ object does not support item assignment

Now that we’ve taken a quick revision at tuples, let’s proceed to python syntax.

Python Namedtuple – Syntax

A Python namedtuple lets us access elements in a tuple using names/labels. To define it, we import namedtuple from Python collections module and use the namedtuple() factory function.

>>> from collections import namedtuple
>>> Colors=namedtuple('Colors','red green blue')

Here, we use the function namedtuple().

>>> type(namedtuple)

Output

<class ‘function’>

This takes two arguments-

  1. Tuple name- Here, Colors is the tuple
  2. Python string of fields, separated by spaces- Here, we have three fields- red, green, and blue.

Now, let’s define some python tuples.

>>> red=Colors(red=255,green=0,blue=0)
>>> green=Colors(red=0,green=255,blue=0)
>>> blue=Colors(red=0,green=0,blue=255)
>>> red

Output

Colors(red=255, green=0, blue=0)

We’ll just leave here another way to define a python namedtuple- using a list instead of a string of fields.

>>> pets=namedtuple('pets',['name','age'])
>>> Fluffy=pets('Fluffy',8)
>>> Fluffy

Output

pets(name=’Fluffy’, age=8)

Accessing Elements in a Python Namedtuple

To access an item, we can now use the dot-operator to access a field by its name. We do it this way:

>>> red.red

Output

255

>>> red.green
>>> red.blue

See how simple it makes this? This way, a namedtuple is something like a python dictionary.

But really, python namedtuple is backward-compatible to a regular python tuple. This means that we can access a value using indexing as well.

>>> red[0]

Output

255

>>> red[1]

Finally, you can also access a value using the getattr() function.

>>> getattr(red,'green')

To see what kind of python objects these are, we use the type() function, like we always do.

>>> type(Colors)

Output

<class ‘type’>

>>> type(red)

Output

<class ‘__main__.Colors’>

>>> type(red.red)

Output

<class ‘int’>

How Namedtuple in Python Works?

Let’s see some more things we can do to a namedtuple in python.

1. A Python namedtuple is Immutable

Like its regular counterpart, a python namedtuple is immutable. We can’t change its attributes.

To prove this, we’ll try changing one of the attributes of a tuple of type ‘Colors’.

>>> red.blue=1

Output

Traceback (most recent call last):File “<pyshell#319>”, line 1, in <module>

red.blue=1

AttributeError: can’t set attribute

As is visible, it raises an AttributeError. Hence, we conclude that a python namedtuple is immutable.

2. Converting a Python namedtuple into a Python Dictionary

A namedtuple in Python is much like a dictionary, but if we want to convert it into one, we can:

>>> red._asdict()

Output

OrderedDict([(‘red’, 255), (‘green’, 0), (‘blue’, 0)])

As you can see, we use the ._asdict() function for this. Also, this gives us a Python OrderedDict.

We’ll see that in detail in its own lesson.

3. Creating a namedtuple from a python Iterable

If you have a python list, you can make a namedtuple from it. But for this, you must have defined the format.

>>> Colors._make(['Purple','Violet','Gold'])

Output

Colors(red=’Purple’, green=’Violet’, blue=’Gold’)

 

4. Converting a Python Dictionary into a namedtuple

CoA conversef what we learned in point b, we can turn a dictionary into a namedtuple in Python.

We do this using two asterisks before the dictionary to be passed as an argument to Colors here.

>>> Colors(**{'red':255,'green':0,'blue':0})

Output

Colors(red=255, green=0, blue=0)

5. Checking what fields belong to a Python tuple

For this, we use the _fields attribute.

>>> red._fields

Output

(‘red’, ‘green’, ‘blue’)

6. Changing a Value

Yes, a namedtuple’s attributes are immutable. But we can use the _replace() function to change them.

>>> red._replace(green=1)

Output

Colors(red=255, green=1, blue=0)

Benefits of Python Namedtuple

Of course, no one would be using these if they observed no benefits at all. So, here we go:
1. Unlike a regular tuple, python namedtuple can also access values using names of the fields.

>>> red.red

Output

255

2. Python namedtuple is just as memory-efficient as a regular tuple, because it does not have per-instance dictionaries. This is also why it is faster than a dictionary.

Python Interview Questions on Namedtuple

  1. What is a Namedtuple in Python?
  2. How does Namedtuple work in Python?
  3. What does Namedtuple return in Python?
  4. How do you create a Namedtuple in Python?
  5. Is Namedtuple immutable?

Conclusion

Today, we learned about Python namedtuple. It is just like a regular tuple, apart from the fact that it can also access fields through their names.

This is easy on the programmer. It is also more memory-efficient than a dictionary.

Next, we will discuss some more functions from the collections module. Till give us your valuable feedbacks.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

4 Responses

    • DataFlair Team says:

      Hi Naveen,
      Thanks for giving us a feedback, this means a lot to us. Hope the Python Namedtuples concept is clear to you. You should visit more Python articles, we are sure that you will be glad after reading them. Give your precious review again.
      Best wishes to you.

  1. Sukesh says:

    pets=namedtuple(‘pets’,[‘name’,’age’])

    What is the purpose of ‘pets’ mentioned inside parenthesis

    • DataFlair says:

      The ‘pets’ mentioned inside the parenthesis is the name of the namedTuple. The ‘pets’ outside the parenthesis is the instance of the namedTuple created and helps in assigning the values to the tuple ‘pets’. I hope this explanation is clear.

Leave a Reply

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