nerdexam
Python_Institute

PCEP-30-02 · Question #344

What is the expected result of the following code? ``python rates = (1.2, 1.4, 1.0) new = rates[3:] for rate in rates[-2:]: new += (rate,) print(len(new)) ``

The correct answer is B. 2. Option B is correct because rates[3:] returns an empty tuple () - Python slice operations never raise IndexError, even when the start index exceeds the sequence length. The loop then iterates over rates[-2:], which yields the last two elements (1.4, 1.0), appending each to new…

Question

What is the expected result of the following code?
rates = (1.2, 1.4, 1.0)
new = rates[3:]
for rate in rates[-2:]:
 new += (rate,)
print(len(new))

Options

  • A1
  • B2
  • C5
  • DThe code will cause an unhandled exception

How the community answered

(53 responses)
  • A
    8% (4)
  • B
    74% (39)
  • C
    4% (2)
  • D
    15% (8)

Explanation

Option B is correct because rates[3:] returns an empty tuple () - Python slice operations never raise IndexError, even when the start index exceeds the sequence length. The loop then iterates over rates[-2:], which yields the last two elements (1.4, 1.0), appending each to new one at a time, resulting in a tuple of length 2.

A (1) is wrong because the loop runs twice (two elements in rates[-2:]), so two items get added - not one. C (5) is wrong because rates[3:] contributes zero elements to new, not three; adding the loop's two elements still only gives 2. D is wrong because tuple slicing with an out-of-bounds index is always safe in Python - it silently returns an empty tuple rather than raising an exception (unlike direct indexing like rates[3], which would raise IndexError).

Memory tip: Remember the "slice vs. index" rule - seq[3] on a 3-element sequence crashes, but seq[3:] just gives you (). When you see slicing in code, IndexError is off the table.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice