Skip to content

Blog of David Culley

Start using named tuples instead of regular Python tuples

If you're a Python developer, you surely must've seen code like this:

height = person[2]

This code snippet is not easily understandable. What is person? Is it a list, a tuple, something else? What does the value stored at index 2 represent? You can probably figure out relatively quickly from skimming over the code you're working with if person is a tuple. But still, what is it that is stored at index 2 of that tuple? In this particular case we were lucky enough that the variable was named height, which enabled us to guess that it must be the person's height that is stored at index 2. But more often than not you'll see nondescript code such as h = person[2]. Can you still guess correctly that it's the person's height that is stored at index 2? Can you rule out with absolute certainty that it isn't a Boolean that specifies whether the person is hungry or not? To be sure you'd have to comb through the code to find out. That's why the code snippet above is not easily readable. Wouldn't it be much easier if the code author had written explicitly what that value person[2] is meant to represent? If the author had written person.height instead of person[2]? You can do exactly that with named tuples.