-1

In the official Python documentation said that list.copy() returns a shallow copy of the list. But according to the following code it is deep copy since the change of one list does not lead to the change in another.

>>> num1 = [1,2,3,4,5]
>>> num2 = num1.copy()
>>> num1.append(9)
>>> num1
[1, 2, 3, 4, 5, 9]
>>> num2
[1, 2, 3, 4, 5]

What is the problem? Where is a mistake?

Konrad Rudolph
  • 506,650
  • 124
  • 909
  • 1,183

1 Answers1

2

This example will demonstrate why this is a shallow copy

>>> num1 = [[1,2,3],[4,5,6]]
>>> num2 = num1.copy()
>>> num1[0].append(9)
>>> num1
[[1, 2, 3, 9], [4, 5, 6]]
>>> num2
[[1, 2, 3, 9], [4, 5, 6]]

Since the original list contained mutable elements, the outer copy contains shallow copies to the mutable elements.

Cory Kramer
  • 107,498
  • 14
  • 145
  • 201