Tuples and Dictionaries · Class 11 · CBSE · Science Computer Science

Why can a tuple sometimes be used as a dictionary key while a list cannot? Give one valid tuple-key example and one invalid list-key example.

Practice question from Tuples and Dictionaries (Class 11 · CBSE · Science Computer Science), with the correct answer and a step-by-step solution.

hard · Subjective · Q-27EFC4

Why can a tuple sometimes be used as a dictionary key while a list cannot? Give one valid tuple-key example and one invalid list-key example.

Answer: Dictionary keys must be hashable, and lists are mutable and therefore unhashable. A tuple containing only hashable elements can be used as a key, for example d = {(1, 2): "point"}. The statement d = {[1, 2]: "point"} is invalid because a list cannot be used as a dictionary key.

Solution

Dictionary keys must have a stable hash value. A tuple is hashable only when all its elements are hashable, whereas a list is mutable and unhashable.

More from Tuples and Dictionaries

All of Tuples and Dictionaries

Practise more Computer Science

Sign up free for adaptive practice on this chapter, with instant feedback and hints on every question.

Start practising free

Free to start · No credit card needed