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.
class Foo:
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):
return self.__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 copy import 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.