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'.