Comprehensions & Generators · Question 3 · Easy

A dictionary comprehension maps each number to its square. What is printed?

print({n: n * n for n in range(1, 4)})
  1. {1, 4, 9}
  2. {1: 1, 2: 4, 3: 9}
  3. [(1, 1), (2, 4), (3, 9)]
  4. {0: 0, 1: 1, 2: 4}
Answer and explanation

Answer: B. {1: 1, 2: 4, 3: 9}

Explanation: key: value inside braces builds a dictionary. range(1, 4) gives 1, 2 and 3, and each is paired with its square.

Previous: A comprehension with an if clause keeps only the passing marks (60 or more)… · Next: A set comprehension collects the first letter of each word. What does len…

Practise comprehensions & generators

Try a fresh set of comprehensions & generators questions with an explanation after every answer, free and without signing up: Comprehensions & Generators practice. Or sit a full placement mock test.

More comprehensions & generators questions

More python practice

Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge