Thursday, August 12, 2010

Python named tuples

Python named tuples are a good way to make your code more readable when using tuples. Instead of using numerical dereferences like:
In [49]: c=('abc','adefa','aaaa')

In [50]: c[0]
Out[50]: 'abc'
You can create a namedtuple class:
In [51]: from collections import namedtuple 

In [53]: MyTup = namedtuple('MyTup','first second other')

In [54]: t = MyTup("aa","bb",other="cc")

In [55]: t.first 
Out[55]: 'aa'

No comments: