Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list.pop() modifies original list (not just copy)

Tags:

python

Situation: After making a copy of the original list I use pop to modify said copy. As it turns out, the original list gets affected by the change.

I even after checking the original list and the copy are not the same object, poping an element of the copy will will pop the same element in the original.

See below for an example of the script. Thanks in advance for your help.

l = [['1412898', 'Jack', 'headache med', '8ET-500'],
     ['1423859', 'Sonny', 'prostate med', '8ET-800'],
     ['1413836', 'Paco', 'headache med', '8ET-500']]

class App(object):
    def __init__(self, info):
        self.fp_rows= info

    def sortbyauditor(self):
        self.fp_rows_copy = self.fp_rows[:]

        print self.fp_rows is self.fp_rows_copy
        for i in self.fp_rows_copy:
            i.pop(1)
        print self.fp_rows_copy
        print self.fp_rows

app= App(l)
app.sortbyauditor()
like image 854
solid Avatar asked Jun 25 '26 19:06

solid


1 Answers

some_list[:] is only a shallow copy. You seem to need a deep copy

from copy import deepcopy

copy = deepcopy(some_list)

Edit

To understand why "one objects affects the other" take a look at the id of each list:

original = [[1, 2], [3, 4]]
shallow = original[:]
deep = deepcopy(original)

print([id(l) for l in original])
# [2122937089096, 2122937087880]

print([id(l) for l in shallow])
# [2122937089096, 2122937087880]

print([id(l) for l in deep])
# [2122937088968, 2122937089672]

You can see that the ids of the lists in original are the same as the ids in shallow. That means the nested lists are the exact same objects. When you modify one nested list the changes are also in the other list.

The ids for deep are different. That are just copies. Changing them does not affect the original list.

like image 74
Wombatz Avatar answered Jun 27 '26 07:06

Wombatz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!