list vs tuple

Fredrik Lundh fredrik at pythonware.com
Wed Mar 28 13:57:11 EST 2001


Mark Pilgrim wrote
> It was my understanding that only tuples containing immutable objects could
> be used as dictionary keys.  For instance, (1,2,3) can be, and ("a","b","c")
> can be, but ([1,2,3], ["a","b","c"]) can not, because the underlying objects
> could mutate and cause problems.  (Wow, that sounds like a bad sci-fi
> movie.)  Is this true?

no python interpreter within reach today?

>>> d = {}
>>> d[(1, 2, 3)] = 1
>>> d[("a", "b", "c")] = 2
>>> d[([1, 2, 3], ["a", "b", "c"])] = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unhashable type

Cheers /F

PS. For some reason, nobody has mentioned that tuples and lists
tend to be *used* in different ways, also when you're not using
them as dictionary keys:
- Tuples are typically used to group heterogenous sets
  of data, just like structs/records in other languages.
- Lists are used as containers, to store homogenous sets
  of data, just like arrays/vectors in other languages.





More information about the Python-list mailing list