9

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.

1

3 Answers 3

15

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.
Sign up to request clarification or add additional context in comments.

1 Comment

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.
10

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)])

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.