Back

Explore Courses Blog Tutorials Interview Questions
0 votes
7 views
in Python by (50.2k points)

My main question is what is named tuple, and how we can use it in our program? And also one more thing, why should I use named tuples rather than normal tuples?

1 Answer

0 votes
by (108k points)

Please be informed that the named tuples are fundamentally easy-to-create, lightweight object types. Named tuple objects can be referenced using object-like variable dereferencing or the standard tuple syntax. They are immutable objects.

This leads to code like the following:

pt1 = (1.0, 5.0)

pt2 = (2.5, 1.5)

from math import sqrt

line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)

Using a named tuple it becomes more readable:

from collections import namedtuple

Point = namedtuple('Point', 'x y')

pt1 = Point(1.0, 5.0)

pt2 = Point(2.5, 1.5)

from math import sqrt

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

But, named tuples are still backwards compatible with normal tuples, so the following will still execute:

Point = namedtuple('Point', 'x y')

pt1 = Point(1.0, 5.0)

pt2 = Point(2.5, 1.5)

from math import sqrt

# use index referencing

line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)

 # use tuple unpacking

x1, y1 = pt1

If you want to know more about tuples then do refer to the python course that will help you out in a better way. 

Related questions

0 votes
1 answer
asked Nov 26, 2020 in Python by Rekha (2.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...