Late-binding of function defaults (was Re: What is a function parameter =[] for?)

Ben Finney ben+python at benfinney.id.au
Wed Nov 25 14:55:24 EST 2015


Chris Angelico <rosuav at gmail.com> writes:

> This is a distinction I generally make. Putting it another way: a list
> has the same meaning regardless of how many items are on it (for
> instance, a shopping list is still a shopping list whether it has five
> or fifty items on it), where a tuple is a package where each element
> has a specific meaning […]

Yes. The disctinction is even clearer, I find, by saying that the
*meaning of the position* in the sequence is significant for a tuple,
not significant for a list.

That is, the ‘2’ in ‘cartesian_point = (2, 3)’ means something different
than in ‘cartesian_point = (3, 2)’.

Whereas the ‘2’ in ‘test_scores = [2, 3]’ means exactly the same as in
‘test_scores = [3, 2]’.

If each position in the sequence gives the value there a different
menaning, use a tuple; if not, use a list.

> Nothing in the language enforces this, but the mutability of lists
> does tend to align well with things that can grow and shrink, and the
> immutability of tuples makes them more like strings or complex numbers
> (in fact, a complex number is basically a tuple of two floats).

Not only the growing and shrinking, but the re-ordering of items in a
list should not change the meaning of its items.

If you can ‘sort’ the sequence and the items still mean exactly what
they did before, then a tuple is the wrong type to use, semantically.

-- 
 \       “Crime is contagious… if the government becomes a lawbreaker, |
  `\          it breeds contempt for the law.” —Justice Louis Brandeis |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list