How to deep copy a list?

E0_copy is not a deep copy. You don’t make a deep copy using list(). (Both list(…) and testList[:] are shallow copies.) You use copy.deepcopy(…) for deep copying a list. deepcopy(x, memo=None, _nil=[]) Deep copy operation on arbitrary Python objects. See the following snippet – >>> a = [[1, 2, 3], [4, 5, 6]] >>> b … Read more

What is the difference between shallow copy, deepcopy and normal assignment operation?

Normal assignment operations will simply point the new variable towards the existing object. The docs explain the difference between shallow and deep copies: The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances): A shallow copy constructs a new compound object and … Read more

How to clone ArrayList and also clone its contents?

You will need to iterate on the items, and clone them one by one, putting the clones in your result array as you go. public static List<Dog> cloneList(List<Dog> list) { List<Dog> clone = new ArrayList<Dog>(list.size()); for (Dog item : list) clone.add(item.clone()); return clone; } For that to work, obviously, you will have to get your … Read more