Product SiteDocumentation Site

14.3. namedtuple

Named tuples helps to have meaning of each position in a tuple and allow us to code with better readability and self-documenting code. You can use them in any place where you are using tuples. In the example we will create a namedtuple to show hold information for points.
Example 14.3. Named tuple
>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])  #Defining the namedtuple
>>> p = Point(10, y=20)  #Creating an object
>>> p
Point(x=10, y=20)  
>>> p.x + p.y
30
>>> p[0] + p[1]  #Accessing the values in normal way
30
>>> x, y = p      #Unpacking the tuple
>>> x
10
>>> y
20