The named tuples in Python are tuples which can be accessed using named fields and named attributes.
It is always better to make use of the named tuples in your Python code as it improves readability.
We can import namedtuple function from collections module which lets us create named tuples.
Syntax:
from collections import namedtuple
MyTuple = namedtuple('MyTuple', ['field1', 'field2', ...])
Let's take a look at a few examples.
Example 1:
from collections import namedtuple
# A named tuple called 'City' with fields 'name', 'country', and 'population'
City = namedtuple('City', ['name', 'country', 'population'])
london = City('London', 'United Kingdom', 8908081)
new_york = City('New York', 'USA', 8537673)
tokyo = City('Tokyo', 'Japan', 13929286)
print(london.name, london.country, london.population)
print(new_york.name, new_york.country, new_york.population)
print(tokyo.name, tokyo.country, tokyo.population)
Output:
London United Kingdom 8908081
New York USA 8537673
Tokyo Japan 13929286
As you may see, we created a named tuple with named field - City and named attributes - 'name', 'country', and 'population'
We were able to access the files using dot notation.
Let' take a look at another example.
Example 2:
from collections import namedtuple
PlotData = namedtuple('PlotDataXY', ['x', 'y'])
plot = PlotData(2, 5)
print(plot.x)
print(plot.y)

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!