Lists and Tuples

Douglas Alan nessus at mit.edu
Fri Dec 5 08:37:22 CET 2003


David Eppstein <eppstein at ics.uci.edu> writes:

> That's true, but another answer is: you should use tuples for short
> sequences of diverse items (like the arguments to a function).  You
> should use lists for longer sequences of similar items.

I disagree.  You should use a tuple when you wish to not change the
contents once you have constructed the sequence, and otherwise you
should use a list.  Using a tuple can make your code clearer by
letting the reader know from the beginning that the contents won't be
changing.

Fredrik Lundh actually called me names a couple years back for
asserting this, but Python luminary (and rude fellow) or not, he is
dead wrong.

You don't have to take my word for it, though, since Python itself
uses tuples in this manner, in the form of the container used for
excess arguments (excess arguments certainly don't have to be short,
and they are generally homogeneous, not heterogeneous), and Python
Mega Widgets (for example) is littered with code that looks like:

   optiondefs = (
       ('initwait',                 500,            None), # milliseconds
       ('label_background',         'lightyellow',  None),
       ('label_foreground',         'black',        None),
       ('label_justify',            'left',         None),
       ('master',                   'parent',       None),
       ('relmouse',                 'none',         self._relmouse),
       ('state',                    'both',         self._state),
       ('statuscommand',            None,           None),
       ('xoffset',                  20,             None), # pixels
       ('yoffset',                  1,              None), # pixels
       ('hull_highlightthickness',  1,              None),
       ('hull_highlightbackground', 'black',        None),
   )

In the above case we see tuples being used both as records *and* as an
arbitrary-length sequence of homogenious elements.  Why is a tuple
being used in the latter case, rather than a list?  Because the
sequence isn't going to be modified.

|>oug




More information about the Python-list mailing list