Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deepcopy of two lists

I have two lists in python, which stores some class instances in different manners (e.g. order). Now, I would like to create a copy of these two lists for some purpose (independent from the existing ones). To illustrate my problem clearly, I created a demo code below.

import copy

class Node:
    def __init__(self):
        self.node_id = 0

node = Node()
list1 = [node]
list2 = [node]

u_list1 = copy.deepcopy(list1)
u_list2 = copy.deepcopy(list2)

id1 = id(list1[0])
id2 = id(list2[0])
u_id1 = id(u_list1[0])
u_id2 = id(u_list2[0])

By using deepcopy operation, I created two new lists u_list1 and u_list2 that are independent from list1 and list2, which is what I need. However, I find an issue. The node instance in u_list1 and u_list2 are also independent now. They have different addresses in memory. Is it possible that the same instances in u_list1 and u_list2 still share one address just like instances in list1 and list2?

What I need is id1 = id2, u_id1 = u_id2, while id1 != u_id1.

like image 667
Jiawei Lu Avatar asked Jul 28 '20 23:07

Jiawei Lu


People also ask

How do you Deepcopy a list in Python?

To make a deep copy, use the deepcopy() function of the copy module. In a deep copy, copies are inserted instead of references to objects, so changing one does not change the other.

What is Deepcopy () in Python?

What is Deep copy in Python? A deep copy creates a new compound object before inserting copies of the items found in the original into it in a recursive manner. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original.

How do I make a deep copy of a list?

To create a shallow copy of a list of lists, use the list. copy() method that creates a new outer list with copied references to the same inner lists. To create a deep copy with copied inner lists, import the copy library and call copy. deepcopy(list) to copy both the inner and outer lists.

Does list () create 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.


1 Answers

You could use deepcopy's memo aspect by deep copying them together:

u_list1, u_list2 = copy.deepcopy((list1, list2))

From the documentation (emphasis mine):

Two problems often exist with deep copy operations that don’t exist with shallow copy operations:

  • Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.

  • Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.

The deepcopy() function avoids these problems by:

  • keeping a memo dictionary of objects already copied during the current copying pass; and
like image 192
Kelly Bundy Avatar answered Sep 25 '22 15:09

Kelly Bundy