Greetings! Today, I would like to briefly go over one of my favorite and seemingly lesser-known Python modules. The collections module (Python 2) contains a few useful container objects that when implemented in the right scenerios will speed up your code while also making it more readable. Python 3 added a few more that aren't in Python 2 which I'm not fully familiar with yet, so I would like to just go over one of the objects I use that is common to both versions of Python.
collections.namedtuple -- "Factory function for creating tuple subclasses with named fields"
The namedtuple object is a subclass of the tuple object. It functions just like a tuple does, because of subclass inheritance, so it can be used anywhere a tuple can and without overhead. What makes namedtuples so great is that you also get named attributes for the values in it. This is very useful for situations where you know exactly what type values will be in the tuple and their position. Instead of accessing the values by index (which is still something you can do with the namedtuple), you would instead do the more readable Pythonic thing and use the named attributes.
To use the namedtuple, you will want to have a list or other such ordered sequence item with strings for naming the attributes. Then, the object is instantiated with that list and a name for your new namedtuple object. The following code will use the namedtuple factory function from the module to create a new "Person" class.
>>> from collections import namedtuple
>>> values = ('name', 'age', 'sex')
>>> Person = namedtuple('Person', values)
Now we can use this new Person class to make Person objects with some attributes you might expect a person to have, which I stored in a tuple as "values".
>>> sarah = Person('Sarah', 25, 'Female')
Person(name='Sarah', age=25, sex='Female')
Good stuff, right? Here are some things you can do with it now. You'll see that it can be treated just like a tuple or like the namedtuple it is.
('Sarah', 25, 'Female')
>>> for (key, value) in zip(values, sarah):
print(key, '-', value)
name - Sarah
age - 25
sex - Female
So there you have it, just one simple use for the namedtuple. Let me know if this guide was helpful and/or well-written enough. If so, you can count on there being a part two some time in the near future. Also, I'll be glad to answer any questions about this guide or namedtuples. Thanks for reading, and happy coding!