Copy List In Python
Solution 1:
Your original list contains inner lists:
[[0, 'ZZZ', 'XXX', 'YYY', 'AAA', 0, 0],
['BBB', 1, 1, 0, 26, 28, 0], ...
]
The inner list are actually stored as references, i.e.:
[ location-of-list-0,
location-of-list-1, ...
]
When you copied the list, you actually copied a list of references to the same lists stored in your original list. This is called shallow copy, as it copies references rather than contents.
Use deep copy to create a totally separate list.
Illustrations
Original List
Shallow copy
Deep copy
Solution 2:
You need deepcopy
to also copy the objects in the list, and not only the references.
Solution 3:
You should also copy inner lists, so deepcopy
may help you.
Solution 4:
As [:]
does only create a copy-slice of the list the slice is actually applied to, the reference to the objects stay the same.
Using deepcopy does recursively copy every item that can be pointed out.
classFoo:def__init__(self):
self.name = "unknown"def__repr__(self):
return"Foo: " + self.name
def__copy__(self):
f = Foo()
f.name = self.name
return f
def__deepcopy__(self, d):
returnself.__copy__()
lst = [Foo()]
lst[0].name = "My first foo"
lst2 = lst[:]
lst2.append(Foo())
lst2[1].name = "My second foo"
print lst
print lst2
output
[Foo: My first foo] [Foo: My first foo, Foo: My second foo]
lst2[0].name = "I changed the first foo"print lst
print lst2
output
[Foo: I changed the first foo] [Foo: I changed the first foo, Foo: My second foo]
from copyimport deepcopy
lst[0].name = "My first foo"
lst3 = deepcopy(lst)
lst3[0].name = "I changed the first foo again !"print lst
print lst3
output
[Foo: I changed the first foo] [Foo: I changed the first foo again !]
Lists, tuples, etc do support __copy__
and __deepcopy__
method.
Post a Comment for "Copy List In Python"