Tuple and namedtuple#
Tuple#
Tuples are immutable data structure. They are homogeneous/heterogeneous.
Order have meaning.
Tuple are faster than list.
Note
What defines tuple is not parenthesis but a comma.
eg:
tup = 1,
num = (1)
type(tup), type(num)
(tuple, int)
Namedtuple#
It is just a fancy way to instanciating a tuple object so that we can access the element using dot notation like in python classes.
It is class generator.
Inherits the tuple class.
from collections import namedtuple
x = ['x','y'] # or ('x','y) or "x y" or "x,y"
Point2d =namedtuple('Point2d',x)
coord = Point2d(10,20)
coord
Point2d(x=10, y=20)
Accessing Data in named tuple#
x,y = coord
# or
x = coord[0]
y = coord[1]
# or using field name
x = coord.x
y = coord.y
print(x,y,sep=",")
10,20
isinstance(coord,tuple)
True
Person = namedtuple("Person","name email address contact religion education")
Person._fields
('name', 'email', 'address', 'contact', 'religion', 'education')