The problem with using tuples and lists to hold structures

August 18, 2008

If you need to hold several bits of data about something in Python, it's awfully tempting to just put everything into a tuple or a list and be done with it; it's certainly the easiest way, and so crops up often.

(I've read that that Pythonic way to decide between a list and a tuple is whether or not the data is all the same type, in which case you use a tuple, or different types, in which case you use a list. I don't bother paying attention to this; I generally use a tuple if the data elements don't get changed and a list if they do.)

The problem with using lists and tuples instead of actual structures for this is that you are stuffing structured data into unstructured objects. The result is that the structure of the data only exists implicitly in your code, instead of explicitly in the objects. This is both harder to read and more prone to errors (especially since the structure of the data is going to be in more than one place, all of which had better agree).

All of this makes me think that I should be using some sort of structures in my Python code much more than I am now. Even if the idiom itself takes some explaining, I think that the overall code will be simpler and clearer.

(And the basic version is not all that much code, either.)

Update: I was wrong about the Python use of lists and tuples; it is lists that are for data that is all the same type, and tuples for data that is a different type. See the comments for details.


Comments on this page:

From 24.130.22.87 at 2008-08-19 23:34:16:

Any idea where you read about that idiom? It doesn't seem to make much sense in a language with heterogeneous lists, though it's certainly the case in other languages that require homogeneous lists but allow heterogeneous tuples (like SML). In my book, Python tuples are just frozen-lists! (A la frozenset: http://docs.python.org/lib/types-set.html)

- Chris Leary

By cks at 2008-08-20 01:47:59:

It turns out that I had this backwards; it is lists that are for things that are all of the same type, and tuples for mixed things. The original remark about this comes from Guido van Rossum back in 2003.

Written on 18 August 2008.
« Thinking about the best way to handle command registration
An illustration of why syntactic sugar matters »

Page tools: View Source, View Normal.
Search:
Login: Password:

Last modified: Mon Aug 18 22:32:23 2008
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.