Alphonse
Alphonse

Reputation: 237

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.

Upvotes: 9

Views: 720

Answers (3)

Olivier Verdier
Olivier Verdier

Reputation: 49146

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.

Upvotes: 4

Scott Griffiths
Scott Griffiths

Reputation: 21925

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

Upvotes: 10

Max Shawabkeh
Max Shawabkeh

Reputation: 38603

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.

Upvotes: 15

Related Questions