What are "named tuples" in Python?

PythonServer Side ProgrammingProgramming

<p style="">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.</p><pre class="prettyprint notranslate">&gt;&gt;&gt; student=(1,&quot;Ravi&quot;,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</pre><p style="">Named tuple is defined with field names specified in its definition. namedtuple() factory function allows creation of tuple &nbsp;with name fields. Field values can now be accessed by name in addition to index. The function is defined in collections module</p><pre class="prettyprint notranslate">&gt;&gt;&gt; from collections import namedtuple</pre><pre class="prettyprint notranslate">&gt;&gt;&gt; student=namedtuple(&#39;student&#39;, (&#39;rollno, name, age, marks&#39;)) &gt;&gt;&gt; s1=student(1,&quot;Ravi&quot;, 23, 546) &gt;&gt;&gt; s1 student(rollno=1, name=&#39;Ravi&#39;, age=23, marks=546) &gt;&gt;&gt; s1.rollno 1 &gt;&gt;&gt; s1.name &#39;Ravi&#39; &gt;&gt;&gt; s1.age 23 &gt;&gt;&gt; s1.marks 546</pre>
raja
Updated on 18-Feb-2020 08:19:20

Advertisements