[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Can tuples be replaced with lists all the time?

On Sun, Feb 23, 2014 at 3:06 PM, Sam <lightaiyee at gmail.com> wrote:
> My understanding of Python tuples is that they are like immutable lists. If this is the cause, why can't we replace tuples with lists all the time (just don't reassign the lists)? Correct me if I am wrong.

One reason is performance/efficiency. If Python knows this is never
going to change, it can save some effort. But a more important reason
is hashability.

>>> mapping = {}
>>> key = (1,2)
>>> mapping[key] = "Hello"
>>> key = (1,3)
>>> mapping[key] = "World"
>>> key = (2,3)
>>> mapping[key] = "!"
>>> mapping
{(1, 2): 'Hello', (1, 3): 'World', (2, 3): '!'}

You can't do this with lists:

>>> key = [1,2]
>>> mapping[key]
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
TypeError: unhashable type: 'list'

This is because any two tuples are either equal or not equal, they
can't be otherwise. I can create another tuple and look up something
in the above mapping:

>>> mapping[1,3]

But with lists, their equality can change.

>>> lst1 = [1,2]
>>> lst2 = [1,3]
>>> lst1 == lst2
>>> lst1[1] += 1
>>> lst1 == lst2
>>> lst1[1] += 1
>>> lst1 == lst2

So it would be very difficult and dangerous to try to use a list as a
dictionary key. The only safe way to do it is by identity, and that's
only useful in a very small set of situations. So Python happily
declares that a tuple can be a dict key and a list can't, and that's
now a key (if you'll excuse the pun) difference between them.