Lists vs tuples (newbie)

Duncan Booth duncan.booth at invalid.invalid
Thu May 24 08:59:29 EDT 2007


"Hendrik van Rooyen" <mail at microcorp.co.za> wrote:

> "Duncan Booth" <d....b...h at invalid.invalid> wrote:
>> "Hendrik van Rooyen" <mail at microcorp.co.za> wrote:
>> 
>> > Aside from the hashing issue, there is nothing that a tuple can do
>> > that can't be done as well or better by a list.
>> 
>> There are a few other cases where you have to use a tuple, for
>> example in a try..except statement the exception specification must
>> be an exception to be caught or a tuple of exception specifications:
>> a list won't work to catch multiple exceptions.
> 
> Esoteric - But I stand corrected...
> 
> any other "must use a tuple's " ?
> 
> Seems they all fall into a class that can be described as required by
> the language - I was thinking data.
> 
There used to be several other situations where a tuple was required but I 
can't think of any others which still exist.

So far as data is concerned, the same reason that exceptions require tuples 
could arise in your own code:

If you look at the definition of the except clause expression (simplified 
to remove the deprecated string option):

> An object is compatible with an exception if it is the class or a base
> class of the exception object or a tuple containing an item compatible 
> with the exception

you'll see that it is impossible for this structure to contain any loops. 
An equivalent structure using lists instead of tuples could contain loops 
and any code which searched it for a match would have to account for this 
somehow.

So, anywhere you want a tree structure with a guarantee that it does not 
contain any loops it may be appropriate to use tuples to represent the 
structure.



More information about the Python-list mailing list