Python Named Tuples Examples

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.


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.population)
print(,, new_york.population)
print(,, tokyo.population)


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)

Python Named Tuples Example


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap