nerdexam
Python_Institute

PCEP-30-02 · Question #14

What is the expected output of the following code? ``python 1 w = [7, 3, 23, 42] 2 x = w[1:] 3 y = w[1:] 4 z = w 5 y[0] = 10 6 z[1] = 20 7 print(w) ``

The correct answer is B. [7, 20, 23, 42]. B is correct because z = w creates an alias - both z and w point to the exact same list object in memory, so z[1] = 20 directly mutates w, changing index 1 from 3 to 20. A is wrong because it ignores the aliasing on line 4; z[1] = 20 does change w, so the list cannot remain [7…

Question

What is the expected output of the following code?
1 w = [7, 3, 23, 42]
2 x = w[1:]
3 y = w[1:]
4 z = w
5 y[0] = 10
6 z[1] = 20
7 print(w)

Options

  • A[7, 3, 23, 42]
  • B[7, 20, 23, 42]
  • C[10, 20, 23, 42]
  • D[10, 20, 23, 42]

How the community answered

(40 responses)
  • A
    8% (3)
  • B
    85% (34)
  • C
    5% (2)
  • D
    3% (1)

Explanation

B is correct because z = w creates an alias - both z and w point to the exact same list object in memory, so z[1] = 20 directly mutates w, changing index 1 from 3 to 20.

A is wrong because it ignores the aliasing on line 4; z[1] = 20 does change w, so the list cannot remain [7, 3, 23, 42].

C and D are identical and both wrong because y = w[1:] creates a brand-new list (a shallow copy of a slice), so y[0] = 10 only modifies y - w is completely unaffected by that assignment.

Memory tip: Think of = with a slice (w[1:]) as "cut and copy" - you get a fresh list. Think of = without a slice (z = w) as "copy the sticky note pointing to the same box" - both names refer to one object, so changes through either name affect the same underlying data.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice