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
- Consider the following Python code: d = {"a": 1, "b": 2}; d["a"] = d["b"]. What will be the value of d after execution?
- Explain why t = (1, 2, [3, 4]) allows t[2].append(5) but does not allow t[2] = [3, 4, 5].
- What is printed by the following Python code? d = {"a": 10, "b": 20}; d["c"] = d.pop("a"); print(d["c"], len(d))
- What is printed by the following Python code? t = (4, 7, 9, 7); print(t.index(7), t.count(7))
Practise more Computer Science
Sign up free for adaptive practice on this chapter, with instant feedback and hints on every question.
Start practising freeFree to start · No credit card needed