In Python, what is the value of `x` after executing: `x = [1, 2, 3]; y = x; y.append(4)`?

Answer and explanation

Correct answer: B. `[1, 2, 3, 4]`

  1. Step 1: In Python, lists are mutable objects, and variable assignment copies object references, not values.
  2. Step 2: `y = x` makes both `y` and `x` point to the exact same list in memory. Appending 4 via `y` modifies that shared object, so `x` evaluates to `[1, 2, 3, 4]`.
Answer
`[1, 2, 3, 4]`.
Why not the others: '`[1, 2, 3]`' assumes assignment performs a deep value copy; '`[4]`' overwrites the list; '`[1, 2, 3, 4, 4]`' duplicates the append operation.

Practise more Python Programming, Data Structures, Algorithms, Networks and Cybersecurity.

Free questions with an explanation for every one, and full timed Saudi Secondary School Certificate mock tests.

In Python, what is the… | Saudi Secondary School Certificate