lists v. tuples

Ninereeds stephenhorne100 at
Mon Mar 17 13:56:24 CET 2008

On Mar 17, 11:49 am, MartinRineh... at wrote:
> What are the considerations in choosing between:
>    return [a, b, c]
> and
>     return (a, b, c) # or return a, b, c
> Why is the immutable form the default?

My understanding is that the immutable form is not the default -
neither form is a default. The syntax for mutable lists requires
square brackets. The syntax for immutable tuples only requires commas.
However, commas are also used for other purposes. The parens for
tuples are the same parens that might wrap any subexpression, in this
case guarding against misinterpretation of commas. Since the parens
are normally included for consistency as well as disambiguation, they
end up being part of the tuple psychologically, but to Python itself
they are separate.

Personally, I'd make the parens compulsory so that mindsets and
language specification are better aligned. If, that is, I was
inventing a new language. But you can be sure that there's plenty of
code out there that would break if a change like that was made now.

As for choosing, if you never plan to modify the members of the
sequence, a tuple expresses that intent and allows Python to enforce
it. Some operations on tuples are probably also more efficient as a
result. That said, 90%+ of the time I use a list either way. After
all, as requirements change I might find I do need to modify after

A change from tuple to list in any non-trivial case would require a
thorough test suite to ensure that all cases are updated correctly
(partly because Python is dynamically typed), and ashamed as I am to
admit it, my test suites are rarely that thorough. Without that
testing, there might be an obscure case where you still create a
tuple, and that tuple gets passed to code that expects a list and
tries to replace an element.

More information about the Python-list mailing list