[Tutor] Details regarding namedtuple

Gursimran Maken gursimran.maken at gmail.com
Sat Sep 14 13:25:08 EDT 2019


Hi All,

I would like to understand the use of first argument i.e. typename in
namedtuple collection.
collections.namedtuple (typename, field_names)

Example 1:
from collections import namedtuple
person = namedtuple ('person', 'age gender')
Sam = person(age=12, gender='M')
Sam.age

Example 2:
from collections import namedtuple
person = namedtuple ('xyz', 'age gender')
Sam = person(age=12, gender='M')
Sam.age
Pam = xyz(age=22, gender='F')
Pam.age

In example 1, both typename and variable name are same i.e. "person", and
we we print Sam.age we get output as 12.

In example 2, both typename and variable name are different i.e. "person"
and "xyz" respectively, and we we print Sam.age we get output as 12 but
when we type below statement we get an error, why?
Pam = xyz(age=22, gender='F')

Thanks in advance,
Gursimran.


More information about the Tutor mailing list