ProgrammingModerateTCS NQT · Wipro pattern

What is printed?

What is printed?
x = [1, 2, 3]
y = x[:]
y[0] = 9
z = x
z[1] = 8
print(x)
  1. A. [9, 2, 3]
  2. B. [1, 8, 3]
  3. C. [1, 2, 3]
  4. D. [9, 8, 3]

Correct answer: B. [1, 8, 3]

x[:] makes a (shallow) copy, so changing y does not touch x. z = x is an alias, so z[1] = 8 changes x. Result: [1, 8, 3].

More Python Programming questions

Exams that ask this topic