nerdexam
Python_Institute

PCEP-30-02 · Question #4

What is the expected output of the following code? ``python data = (1, 2, 4, 8) data = data[-2:-1] data = data[-1] print(data) ``

The correct answer is B. 4. Option B is correct because the final line data = data[-1] uses indexing, not slicing, which extracts the bare integer 4 from the tuple (4,) - indexing always returns the element itself, never a tuple. Tracing the steps: data[-2:-1] slices the original tuple to produce (4,) (a…

Question

What is the expected output of the following code?
data = (1, 2, 4, 8)
data = data[-2:-1]
data = data[-1]
print(data)

Options

  • A(4)
  • B4
  • C(4,)
  • D44

How the community answered

(61 responses)
  • A
    7% (4)
  • B
    80% (49)
  • C
    10% (6)
  • D
    3% (2)

Explanation

Option B is correct because the final line data = data[-1] uses indexing, not slicing, which extracts the bare integer 4 from the tuple (4,) - indexing always returns the element itself, never a tuple.

Tracing the steps: data[-2:-1] slices the original tuple to produce (4,) (a one-element tuple containing 4), then data[-1] indexes into that tuple, yielding the integer 4.

Why the distractors fail:

  • A - (4): This is a syntax trick; (4) is just 4 with redundant parentheses, not a tuple - and either way, indexing doesn't return a tuple.
  • C - (4,): This would be the result after line 2 (data[-2:-1]), but line 3 then strips the tuple wrapper via indexing, so you never print the tuple.
  • D - 44: There is no string concatenation or repetition anywhere in the code; this is a distractor for those who confuse the double-digit result with some operation on 4.

Memory tip: The comma makes the tuple - (4,) is a tuple, (4) is just an integer in parentheses. And remember: slicing always returns a container of the same type, but indexing returns the element itself.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice