lists v. tuples

Duncan Booth duncan.booth at invalid.invalid
Mon Mar 17 09:31:53 EDT 2008


MartinRinehart at gmail.com wrote:

> What are the considerations in choosing between:
> 
>    return [a, b, c]
> 
> and
> 
>     return (a, b, c) # or return a, b, c
> 
A common explanation for this is that lists are for homogenous 
collections, tuples are for when you have heterogenous collections i.e. 
related but different things.

If you follow this line of argument then when you want to return some 
values from a function, e.g. url, headers and data a tuple would be the 
appropriate thing to use.

If you really are returning a homogenous collection (e.g. top 5 urls) 
then a list would be more appropriate.

Another way to look at it is what you expect the caller to do with the 
results. If they are just going to unpack a fixed set of values then a 
tuple makes sense. If you write:

    return url, headers, data

then the caller writing:

   url, headers, data = frobozz()

has a certain symmetry.

It isn't set in stone of course: use whatever you want or whatever feels 
right at the time.

> Why is the immutable form the default?
> 
It isn't. It uses whichever type you specify but tuples may involve a 
little less typing.



More information about the Python-list mailing list