Python : What are named tuples

Each kind of namedtuple is represented by its own class, created by using the namedtuple() factory function. The arguments are the name of the new class and a string containing the names of the elements.

You can basically think of namedtuples as a very quick way of creating a new object/class type with some attribute fields. For example:

from collections import namedtuple
Dog = namedtuple('Dog','age breed name')

sam = Dog(age=2,breed='Lab',name='Sammy')

frank = Dog(age=2,breed='Shepard',name="Frankie")

We construct the namedtuple by first passing the object type name (Dog) and then passing a string with the variety of fields as a string with spaces between the field names. We can then call on the various attributes:

__author__ = ‘asee2278’

from collections import namedtuple

dog = namedtuple(‘Dog’,”name color size”)
kallu = dog(name=”kallu”, color=”black”, size=”small”)

Container = namedtuple(‘Container’, [‘name’, ‘date’, ‘foo’, ‘bar’])
mycontainer = Container(‘kallu’, ’07’, ‘foovalue’, ‘barvalue’)
print mycontainer

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.