ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
a = [[1, 2], [3]]
b = a[:]
b[1].append(4)
b.append([5])
print(a, b, len(a))
  1. A. [[1, 2], [3, 4]] [[1, 2], [3, 4], [5]] 3
  2. B. [[1, 2], [3, 4]] [[1, 2], [3, 4], [5]] 2
  3. C. [[1, 2], [3]] [[1, 2], [3, 4], [5]] 2
  4. D. [[1, 2], [3, 4]] [[1, 2], [3, 4]] 2

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

a[:] copies only the outer list. b[1] and a[1] are the same inner list, so appending 4 shows in both. appending [5] changes only b.

More Python Programming questions

Exams that ask this topic