Subscribe to Tech With Tim!
Named Tuple
Like the Counter object namedtuple is another data type within the collections module. It is used to give names to the elements within a tuple object and make for easier code readability. When you create a namedtuple constructor it looks something like this:
import collections from collections import namedtuple Point = namedtple("name", "paramater1, parameter2, parameterx") p = Point(1,4,5) print(p) # prints name(parameter1=1 ,parameter2=4 , parameterx=5)
Indexing
Because each of our elements in the tuple now has a name attached to it we are able to access elements by name.
import collections from collections import namedtuple Point = namedtple("Point", "x y") p = Point(1,4) print(p.x) # prints 1 print(p.y) # prints 4 print(p) # prints Point(x=1, y=4)