PCEP-30-02 · Question #240
QUESTION 268 What is the expected behavior of the following program? foo = (1, 2, 3) foo.index(0)
The correct answer is D. The program will cause a ValueError exception. Calling foo.index(0) on the tuple (1, 2, 3) raises a ValueError because the value 0 does not exist in the tuple - index() throws ValueError whenever the searched value is absent, just as it does for lists. Why distractors are wrong: A (AttributeError): Tuples do have an…
Question
Options
- AThe program will cause a AttributeError exception.
- BThe program will cause a SyntaxError exception.
- CThe program will output 1 to the screen.
- DThe program will cause a ValueError exception.
- EThe program will cause a TypeError exception.
How the community answered
(60 responses)- A2% (1)
- B5% (3)
- C2% (1)
- D83% (50)
- E8% (5)
Explanation
Calling foo.index(0) on the tuple (1, 2, 3) raises a ValueError because the value 0 does not exist in the tuple - index() throws ValueError whenever the searched value is absent, just as it does for lists.
Why distractors are wrong:
- A (AttributeError): Tuples do have an
.index()method, so no AttributeError occurs - it's a valid tuple method. - B (SyntaxError): The code is syntactically valid Python; a SyntaxError only occurs when the code itself is malformed (missing colons, mismatched brackets, etc.).
- C (output 1): Even if
0were in the tuple,.index()returns the integer index position silently - it doesn't print anything, and0isn't there regardless. - E (TypeError): A TypeError would occur if you passed an incompatible type to the method (e.g., wrong number of arguments), but an integer argument is perfectly valid here.
Memory tip: Think "ValueError = the Value you asked for can't be found." Whenever a search method (.index(), .remove()) can't locate the target value in a sequence, Python raises ValueError - not an attribute or type error, because the method and type are both correct.
Community Discussion
No community discussion yet for this question.