Module mutability
source code
Tuples differ from lists in not being MUTABLE:
>>> X = (24, 3.14, 'w', 7)
>>> X[1] = 2.7
...
TypeError: object does not support item assignment
What this means, among other things, is that tuples, but not lists,
may be used as keys in dictionaries (they are 'hashable'):
>>> D = {}
>>> D[X] = 41
>>> D
{(24, 3.1400000000000001, 'w', 7): 41}
There is one other non mutable sequence type that can be used as a
dictionary key, of course: strings
>>> 'spin'[2]
'i'
>>> 'spin'[2]= 'a'
...
TypeError: object does not support item assignment
>>> D['spin'] = 40
>>> D
{(24, 3.1400000000000001, 'w', 7): 41, 'spin': 40}
Note that a single dictionary may employ an arbitrary collection of
key types, as long as they are all hashable.
Note the difference in the following:
>>> X = []
>>> Y = []
>>> X.append('a')
>>> X
['a']
>>> Y
[]
and the following:
>>> X = []
>>> Y = X
>>> X.append('a')
>>> X
['a']
>>> Y
['a']
There are times when you really want to avoid mutables, for example,
as a default value for a function parameter.
>>> def foo (e,arg=[]):
... arg.append(e)
... return arg
...
>>> foo(1)
[1]
>>> foo(2)
[1, 2]