1

So I just encountered something weird.

I had problems with copying lists and altering when I started programming, then learned that I had to use my_list.copy() to get an actual copy. Now I just stumbled upon the same effect, despite using list.copy().

So here is an example:

ori = [['1', '2', '3'],['1', '2', '3'],['1', '2', '3'],['1', '2', '3']]
copy = ori.copy()

for i, item in enumerate(copy):
    del copy[i][0]

print('Original list: ', ori)
print('Copy of list: ', copy)

What I expected as output:

Original list: [['1', '2', '3'],['1', '2', '3'],['1', '2', '3'],['1', '2', '3']]
Copy of list: [['2', '3'], ['2', '3'], ['2', '3'], ['2', '3']]

Actual output:

Original list: [['2', '3'],['2', '3'],['2', '3'],['2', '3']]
Copy of list: [['2', '3'], ['2', '3'], ['2', '3'], ['2', '3']]

So I guess my question is: Is this expected behaviour? Do I need to use copy.deepcopy() or is there another solution with built in tools?

I am using Python 3.8.1 on the PC I just had this 'issue'.

n00by0815
  • 184
  • 1
  • 12
  • 2
    This is because you've just done a "shallow" copy. For more info please [read the documentation](https://docs.python.org/3/library/copy.html). Specifically about `copy.deepcopy`. – Hampus Larsson Jun 02 '20 at 12:54
  • 2
    https://stackoverflow.com/questions/28684154/python-copy-a-list-of-lists – animalknox Jun 02 '20 at 12:56
  • Thanks guys, I just read the documentation 2 minutes before posting the question. Guess I must have skipped over the part about collection of objects. @HampusLarsson I don't think your link applies 100%, as I used the built in function. Same logic applies though. – n00by0815 Jun 02 '20 at 13:01
  • 1
    @n00by0815 It does apply 100%. When you call `list.copy()` it calls `copy` on itself, which itself is the same as `copy.copy`. – Hampus Larsson Jun 02 '20 at 13:05

1 Answers1

2

The copy() method returns a shallow copy of the list. Use copy.deepcopy() instead.

Adam Boinet
  • 521
  • 8
  • 22