40.
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
(Python Question) Let us give some numbers part 1**
Is the following line of code valid?
>>> a,b=1,2,3
Pick ONE option
Show answer & explanation
Answer: C. No, too many values to unpack
The assignment a,b=1,2,3 attempts to unpack three values (1, 2, 3) into two variables (a, b), which causes a ValueError. Python's tuple unpacking requires an exact match between the number of values on the right side and the number of variables on the left side. Since there are 3 values but only 2 variables, the code is invalid.
Step-by-step Derivation:
Execution trace:
>>> a,b=1,2,3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
Why it fails:
- Left side: 2 variables (a, b)
- Right side: 3 values (1, 2, 3)
- Mismatch → ValueError
Correct alternatives:
a,b,c=1,2,3(3 variables for 3 values) ✓a,b=1,2(2 variables for 2 values) ✓a,b,*c=1,2,3(using unpacking to capture remaining values) ✓