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.

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) 
Python Named Tuples Example

-

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


Author: Rakesh
Author Info:

Rakesh 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





























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