nerdexam
Python_Institute

PCEP-30-02 · Question #99

Consider the following code. ``python x = [0, 1, 2] x[0], x[2] = x[2], x[0] `` What does the second assignment do?

The correct answer is B. It reverses the list. Option B is correct because x[0], x[2] = x[2], x[0] is a simultaneous swap: Python evaluates the right-hand side (x[2], x[0] → 2, 0) as a tuple before any assignment occurs, then assigns 2 to x[0] and 0 to x[2], transforming [0, 1, 2] into [2, 1, 0] - which is the list…

Question

Consider the following code.
x = [0, 1, 2]
x[0], x[2] = x[2], x[0]
What does the second assignment do?

Options

  • AIt shortens the list.
  • BIt reverses the list.
  • CIt doesn't change the list.
  • DIt extends the list.

How the community answered

(48 responses)
  • A
    2% (1)
  • B
    81% (39)
  • C
    10% (5)
  • D
    6% (3)

Explanation

Option B is correct because x[0], x[2] = x[2], x[0] is a simultaneous swap: Python evaluates the right-hand side (x[2], x[0]2, 0) as a tuple before any assignment occurs, then assigns 2 to x[0] and 0 to x[2], transforming [0, 1, 2] into [2, 1, 0] - which is the list reversed. Option A (shortens) and D (extends) are wrong because tuple unpacking on the left side of = only reassigns existing indices, never adds or removes elements. Option C is wrong because the first and last elements genuinely change places - the list is mutated, not left intact.

Memory tip: Think of the right-hand side as a snapshot taken before anything moves - Python "photographs" both values simultaneously, so there's no accidental overwrite. Whenever you see a, b = b, a, that's always a clean swap.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice