Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
About list copy.
#1
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?
Reply
#2
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.
Reply
#3
(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.
Reply
#4
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]]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why is the copy method name in python list copy and not `__copy__`? YouHoGeon 2 284 Apr-04-2024, 01:18 AM
Last Post: YouHoGeon
  Copy List Not Copying BAbdulBaki 3 630 Aug-19-2023, 02:03 AM
Last Post: perfringo
Question Making a copy list in a function RuyCab 1 1,804 Jul-11-2021, 02:06 PM
Last Post: Yoriz
  Copy List Structure leoahum 2 2,896 Mar-22-2019, 05:40 PM
Last Post: leoahum
  copy list into variable poroton 1 2,607 Aug-10-2018, 07:19 AM
Last Post: Gribouillis
  Copy List [Help Needed] Patricamillie 0 2,226 Jun-11-2018, 10:53 AM
Last Post: Patricamillie
  Which approach is better to copy a list? nexusfactor 6 4,718 Oct-15-2017, 10:45 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020