tags:

views:

185

answers:

3

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.

+11  A: 

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.
Max Shawabkeh
Thanks for your answer! This way I come to know Python more and more..
Alphonse
Likewise, sets are mutable but frozensets are not. So if you need a set as a key, you have to convert it to a frozenset.
FogleBird
+7  A: 

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)])
Scott Griffiths
+2  A: 

In string formatting tuples are mandatory:

"You have %s new %s" % ('5', 'mails') # must be a tuple, not a list!

Using a list in that example produces the error "not enough arguments for format string", because a list is considered as one argument. Weird but true.

Olivier