ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
a = [[1, 2], [3, 4]]
b = [row[:] for row in a]
c = a[:]
a[0][0] = 9
c[1][1] = 7
print(b, c)
  1. A. [[1, 2], [3, 4]] [[9, 2], [3, 7]]
  2. B. [[9, 2], [3, 4]] [[9, 2], [3, 7]]
  3. C. [[1, 2], [3, 4]] [[1, 2], [3, 7]]
  4. D. [[1, 2], [3, 4]] [[9, 2], [3, 4]]

Correct answer: A. [[1, 2], [3, 4]] [[9, 2], [3, 7]]

row[:] makes independent copies of each row, so b is unaffected by a[0][0]. a[:] is only a shallow copy, so c shares the same inner lists and shows both changes made through a and c.

More Python Programming questions

Exams that ask this topic