0

I am copying a list using the list.copy() function. I assume this creates a copy of the first list in a separate memory location and any changes made to the copied list is not performed on the main list.

But i see that the operation is performed on the main list as well.

Please find the code below:

a=[[7, 8], [13, 16], [29], [], [48], [54, 57, 58], [65], [74, 78], [83, 85]]

c=a.copy()

print(c)

l=[24, 48, 54, 65, 74]

for i in c:
    for j in i:
        if j in l:
            i.pop(i.index(j))

print(c)
print(a)

Result is

[[7, 8], [13, 16], [29], [], [48], [54, 57, 58], [65], [74, 78], [83, 85]]
[[7, 8], [13, 16], [29], [], [], [57, 58], [], [78], [83, 85]]
[[7, 8], [13, 16], [29], [], [], [57, 58], [], [78], [83, 85]]

instead of

[[7, 8], [13, 16], [29], [], [48], [54, 57, 58], [65], [74, 78], [83, 85]]
[[7, 8], [13, 16], [29], [], [], [57, 58], [], [78], [83, 85]]
[[7, 8], [13, 16], [29], [], [48], [54, 57, 58], [65], [74, 78], [83, 85]]

I am new to stackoverflow and please let me know if I have made some mistake in posting the question.

1 Answers1

1

When you are using copy, you are not actually creating new list. Instead both the lists are pointing to same data in memory. So, when you modify the one list, other also gets modified. This is called shallow copy.

To create new list, you will have to use Deep copy which can be done either using DeepCopy from copy module or you can use

# python2.*
c= map(list, a)
# python3.*
c = list(map(list, a))
ajay gandhi
  • 545
  • 4
  • 13