import collections
# create a named tuple called Person with fields of first_name, last_name, and age
Person = collections.namedtuple('Person', ('first_name', 'last_name', 'age'))
# Note a named tuple can have fields names as string using a space as a delimiter also see example below
Person = collections.namedtuple('Person', 'first_name last_name age')
# initialize a user as a Person Tuple
user = Person(first_name="John", last_name="Doe", age=21)
# print user named tuple
print(user)
# print user by field names
print(user.first_name, user.last_name, user.age)
# print length of user
print(len(user))
# print first name by index
print(user[0])
# loop through user
for item in user:
print(item)
from collections import namedtuple
A = namedtuple('A', 'a b c')
a = A(1,2,3)
a.b == a[1] # == 2
a == A(1,2,3) # is True
a[2] = 5 # TypeError: 'A' object does not support item assignment
len(a) # == 3
type(a) # <class '__main__.A'>
>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22) # instantiate with positional or keyword arguments
>>> p[0] + p[1] # indexable like the plain tuple (11, 22)
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> p # readable __repr__ with a name=value style
Point(x=11, y=22)