Python · Question 13 · Hard

What will be the output of the following Python code?

import copy

a = [[1, 2], [3, 4]]
b = copy.copy(a)
b[0].append(5)
b.append([6])
print(a)
  1. [[1, 2], [3, 4]]
  2. [[1, 2, 5], [3, 4], [6]]
  3. [[1, 2], [3, 4], [6]]
  4. [[1, 2, 5], [3, 4]]
Answer and explanation

Answer: D. [[1, 2, 5], [3, 4]]

Explanation: copy.copy makes a shallow copy: b is a new outer list holding the same inner lists. Appending to b[0] changes the inner list shared with a, but b.append([6]) only changes b's outer list.

Previous: What will be the output of the following Python code? · Next: What will be the output of the following Python code?

Practise python

Try a fresh set of python questions with an explanation after every answer, free and without signing up: Python practice. Or sit a full placement mock test.

More python questions

More technical & programming practice

Data Structures · Algorithms · Object-Oriented Programming · DBMS · SQL · Operating Systems · Computer Networks · Software Engineering

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge