Python Forum
About list copy. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: About list copy. (/thread-36819.html)



About list copy. - water - Apr-02-2022

I try to create a copy of list via two ways:

a = [[1,2, 3], [4, 5, 6], [7, 8, 9]]
b = a.copy()
b[0].pop(2)
b[1].pop(2)
b[2].pop(2)
a = [[1,2, 3], [4, 5, 6], [7, 8, 9]]
b = []
for i in a:
    b.append(i)

b[0].pop(2)
b[1].pop(2)
b[2].pop(2)
a
Output:
[[1, 2], [4, 5], [7, 8]]
b
Output:
[[1, 2], [4, 5], [7, 8]]
I consider 'b' is a new list, all of operation on 'b' not should be affect original list 'a', the Python document seems not more description for this, someone can explain? or that's a bug?


RE: About list copy. - deanhystad - Apr-02-2022

a is a list that references three other lists. b is a new list, different than a, but b[0] is the same list as a[0]. Use deepcopy to make copies of the contents.


RE: About list copy. - bowlofred - Apr-02-2022

(Apr-02-2022, 08:45 PM)water Wrote: I consider 'b' is a new list, all of operation on 'b' not should be affect original list 'a'

In one sense you are correct. They are independent lists. You can make changes to one and those changes will not appear on the other.

a.append("X")
print(a)
print(b)
Output:
[[1, 2], [4, 5], [7, 8], 'X'] [[1, 2], [4, 5], [7, 8]]
But in your case the elements of the lists are not independent. Your independent lists have references to the same objects. So when you make changes to those objects (not the lists a or b), then the changes appear when you look in the lists.


RE: About list copy. - deanhystad - Apr-03-2022

a = [[1,2, 3], [4, 5, 6], [7, 8, 9]]
b = a.copy()

print("a", id(a), *[id(x) for x in a])
print("b", id(b), *[id(x) for x in b])
Output:
a 1422495046784 1422493081984 1422493084544 1422493081920 b 1422493442112 1422493081984 1422493084544 1422493081920
From the object id's you can see that "a" and "b" are different lists, but that the lists inside "b" are the same lists that are in "a". Your examples change the lists that "a" and "b" both reference.

Using deepcopy
from copy import deepcopy

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = deepcopy(a)

for x in a:
    x.pop(2)
print(a)
print(b)
Output:
[[1, 2], [4, 5], [7, 8]] [[1, 2, 3], [4, 5, 6], [7, 8, 9]]