0
list1 = [
    [0,1,2,3,4],
    [0,1,2,3,4]
]
list2 = list1.copy()
for i in range(len(list2)):
    list2[i].pop(0)
print(list1)#[[1, 2, 3, 4], [1, 2, 3, 4]]
print(list2)#[[1, 2, 3, 4], [1, 2, 3, 4]]

Copying list1 with copy() method in list2 and removing items from nested lists in list2 it shouldn't remove those items in list1. Why it happens?????

Ignatius Reilly
  • 1,594
  • 2
  • 6
  • 15

3 Answers3

1

This occurs because of the difference between a shallow copy vs a deep copy. copy() creates a shallow copy vs deepcopy() creates a deep copy. Here's what the documentation has to say:

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Marcelo Paco
  • 2,732
  • 4
  • 9
  • 26
0

Because the copy() operation is not independent,you could use look at the deepcopy().If you want a nomarl copy operation, you could use deepcopy() to do that.

0

complementing the before answers, you can change to this:

import copy

list1: list[list[int]] = [
    [0, 1, 2, 3, 4],
    [0, 1, 2, 3, 4],
]
list2 = copy.deepcopy(list1)
for pos, items in enumerate(list2):
    list2[pos].pop(0)
print(list1)  # [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
print(list2)  # [[1, 2, 3, 4], [1, 2, 3, 4]]
Magaren
  • 192
  • 8