39.
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
(Python Question) The Lost Dictionary**
What is the output of the following piece of code when executed in Python shell?
>>> a={i: 'A' + str(i) for i in in range(5)}
>>> a
Pick ONE option
Show answer & explanation
Answer: B. {0: 'A0', 1: 'A1', 2: 'A2', 3: 'A3', 4: 'A4'}
The code uses a dictionary comprehension with a typo: in in range(5) (double in). However, Python interprets this as in range(5) in the context of the comprehension, and the expression 'A' + str(i) concatenates the string 'A' with the string representation of each integer from 0 to 4. This creates key-value pairs where keys are 0-4 and values are 'A0', 'A1', 'A2', 'A3', 'A4'.
Step-by-step Derivation:
Step-by-step execution:
- The dictionary comprehension iterates: i = 0, 1, 2, 3, 4
- For each i, the key is i (integer) and the value is 'A' + str(i)
- When i=0: 'A' + '0' = 'A0'
- When i=1: 'A' + '1' = 'A1'
- When i=2: 'A' + '2' = 'A2'
- When i=3: 'A' + '3' = 'A3'
- When i=4: 'A' + '4' = 'A4'
- Result: {0: 'A0', 1: 'A1', 2: 'A2', 3: 'A3', 4: 'A4'}