Practice mode Python

Why can a tuple of numbers be used as a dictionary key, but a list cannot?

Correct answer A. Dictionary keys must be hashable, and lists are mutable and unhashable

Explanation

A dict locates keys through their hash value, which must never change while the key is stored. Mutable objects like lists are therefore unhashable, and using one as a key raises TypeError. A tuple is hashable when all its items are hashable, so (1, 2) works as a key.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.