1 Defining


In [1]:
import collections
Person = collections.namedtuple('Person', 'name age')
bob = Person(name='Bob', age=30)
print('\nRepresentation', bob)


Representation Person(name='Bob', age=30)

In [2]:
jane = Person(name='Jane', age=29)
print('\nField by name:', jane.name)


Field by name: Jane

In [3]:
print('\nField by index')
for p in [bob, jane]:
    print('{} is {} years old'.format(*p))


Field by index
Bob is 30 years old
Jane is 29 years old

Invalid Field name


In [7]:
import collections
try:
    collections.namedtuple('Person', 'name class age')
except ValueError as err:
    print(err)


Type names and field names cannot be a keyword: 'class'

In [8]:
try:
    collections.namedtuple('Person', 'name age age')
except ValueError as err:
    print(err)


Encountered duplicate field name: 'age'

In [9]:
import collections

with_class = collections.namedtuple(
    'Person', 'name class age',
    rename=True)
print(with_class._fields)

two_ages = collections.namedtuple(
    'Person', 'name age age',
    rename=True)
print(two_ages._fields)


('name', '_1', 'age')
('name', 'age', '_2')