What are “named tuples” in Python?

Python Methods and Functions

A tuple object is typically used to define a data structure with comma-separated field values ​​enclosed in parentheses. The value of each field is identified by an index in the tuple.



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

A named tuple is defined by the field names specified in its definition. The namedtuple () factory function allows you to create a tuple with name fields. Field values ​​can now be accessed by name in addition to the index. The function is defined in the collections module

 & gt; & gt; & gt; from collections import named tuple 
 & gt; & gt; & gt; student = namedtuple (`student`, (` rollno, name, age, marks`)) & gt; & gt; & gt; s1 = student (1, "Ravi", 23, 546) & gt; & gt; & gt; s1 student (rollno = 1, name = `Ravi`, age = 23, marks = 546) & gt; & gt; & gt; s1.rollno 1 & gt; & gt; & gt; s1.name `Ravi` & gt; & gt; & gt; s1.age 23 & gt; & gt; & gt; s1.marks 546 







Get Solution for free from DataCamp guru