Python Tutorial

Tuesday, February 19, 2013

Python collections - namedtuple

collections.namedtuple is a factory function for creating tuple subclasses with named fields. It can be used as struct or data container.

All source code available on github

from collections import namedtuple

Point = namedtuple('Point', ['x' ,'y'])

p1=Point(1, 2)
p2=Point(6, 4)

print p1
print p2
print "p1[0]",p1[0],"p1[1]",p1[1]
print "p2.x",p2.x,"p2.y",p2.y

Output:
Point(x=1, y=2)
Point(x=6, y=4)
p1[0] 1 p1[1] 2
p2.x 6 p2.y 4

0 comments:

Post a Comment