Menu Close

How to use named tuples in Python?

Sometimes, we want to use named tuples in Python.

In this article, we’ll look at how to use named tuples in Python.

How to use named tuples in Python?

To use named tuples in Python, we can use the namedtuple function from the collections module.

For instance, we write:

from collections import namedtuple
from math import sqrt

Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)

line_length = sqrt((pt1.x - pt2.x)**2 + (pt1.y - pt2.y)**2)

print(line_length)

We call namedtuple with the class name and the attributes of the named tuple.

We assign the returned class to Point.

Then we can create Point instances by passing in the values for x and y respectively.

Next, we call sqrt with (pt1.x - pt2.x)**2 + (pt1.y - pt2.y)**2 to calculate the Euclidean distance between pt1 and pt2.

And so line_length is 3.8078865529319543.

Conclusion

To use named tuples in Python, we can use the namedtuple function from the collections module.

Posted in Python, Python Answers