Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A list vs. tuple situation in Python

Is there a situation where the use of a list leads to an error, and you must use a tuple instead?

I know something about the properties of both tuples and lists, but not enough to find out the answer to this question. If the question would be the other way around, it would be that lists can be adjusted but tuples don't.

like image 865
Alphonse Avatar asked Feb 17 '10 13:02

Alphonse


2 Answers

You can use tuples as dictionary keys, because they are immutable, but you can't use lists. Eg:

d = {(1, 2): 'a', (3, 8, 1): 'b'}  # Valid.
d = {[1, 2]: 'a', [3, 8, 1]: 'b'}  # Error.
like image 196
Max Shawabkeh Avatar answered Sep 19 '22 14:09

Max Shawabkeh


Because of their immutable nature, tuples (unlike lists) are hashable. This is what allows tuples to be keys in dictionaries and also members of sets. Strictly speaking it is their hashability, not their immutability that counts.

So in addition to the dictionary key answer already given, a couple of other things that will work for tuples but not lists are:

>>> hash((1, 2))
3713081631934410656

>>> set([(1, 2), (2, 3, 4), (1, 2)])
set([(1, 2), (2, 3, 4)])
like image 36
Scott Griffiths Avatar answered Sep 18 '22 14:09

Scott Griffiths