What are "named tuples" in Python?

PythonServer Side ProgrammingProgramming

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
>>> s1.name
>>> s1.age
>>> s1.marks
Published on 01-Jan-2018 19:20:20