-1

First I have written a class I need for some purposes. I have several objects of this class And I have put them in a list. It could be something like:

obj0=created_class(0)
obj1=created_class(1)
List_of_obj=[obj0,obj1]

Now I need a deep copy of the list:

Deep_copy=List_of_obj[:]

My question is: this will instantiate new objects from created class?

user2988577
  • 3,997
  • 7
  • 21
  • 21
  • 1
    it would be trivial to find out: use the `is` operator to inspect the objects. but what makes you think that `[:]` creates a _deep_ copy? –  Jan 09 '18 at 18:14

1 Answers1

0

Slicing ([:]) does not create a deep copy of a list.

>>> class K:
...     def __init__(self, v):
...             self.v = v
...     def __repr__(self):
...             return f'<K: {self.v} ({id(self)})>'
... 
>>> l = [K(1), K(2)]
>>> l
[<K: 1 (4556562104)>, <K: 2 (4556562328)>]
>>> l[:]
[<K: 1 (4556562104)>, <K: 2 (4556562328)>]
>>> from copy import deepcopy
>>> deepcopy(l)
[<K: 1 (4556561880)>, <K: 2 (4556560480)>]

Note where the objects' ids are the same and different.

If your class needs special care when copying, you can find out more from the documentation of the copy module in the standard lib.