Python Namedtuple – Working and Benefits of Namedtuple in Python
Free Python course with 25 real-time projects Start Now!!
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.
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.
As you can see, we define it using parentheses. To access an element, we use indices. (And remember, indexing starts at 0)
What makes a >>> colors python tuple unique is that its values cannot be changed, i.e., it is immutable.
Let’s try changing a value.
Traceback (most recent call last):File “<pyshell#316>”, line 1, in <module> c
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().
This takes two arguments-
- Tuple name- Here, Colors is the tuple
- 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
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
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:
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.
Finally, you can also access a value using the getattr() function.
To see what kind of python objects these are, we use the type() function, like we always do.
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’.
Traceback (most recent call last):File “<pyshell#319>”, line 1, in <module>
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:
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.
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)
5. Checking what fields belong to a Python tuple
For this, we use the _fields attribute.
(‘red’, ‘green’, ‘blue’)
6. Changing a Value
Yes, a namedtuple’s attributes are immutable. But we can use the _replace() function to change them.
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.
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
- What is a Namedtuple in Python?
- How does Namedtuple work in Python?
- What does Namedtuple return in Python?
- How do you create a Namedtuple in Python?
- Is Namedtuple immutable?
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.