Computer >> Computer tutorials >  >> Programming >> Python

What are named tuples in Python?


A tuple object is generally used to define a data structure with comma separated field values put in parentheses. Value of each field is identified by index in tuple.

>>> student=(1,"Ravi",23, 546)
>>> rollno=student[0]
>>> name=student[1]
>>> age=student[2]
>>> marks=student[3]
>>> print (rollno, name, age, marks)
1 Ravi 23 546

Named tuple is defined with field names specified in its definition. namedtuple() factory function allows creation of tuple  with name fields. Field values can now be accessed by name in addition to index. The function is defined in collections module

>>> from collections import namedtuple
>>> student=namedtuple('student', ('rollno, name, age, marks'))
>>> s1=student(1,"Ravi", 23, 546)
>>> s1
student(rollno=1, name='Ravi', age=23, marks=546)
>>> s1.rollno
1
>>> s1.name
'Ravi'
>>> s1.age
23
>>> s1.marks
546