Jiawei Lu
Jiawei Lu

Reputation: 577

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.

Upvotes: 5

Views: 369

Answers (1)

Kelly Bundy
Kelly Bundy

Reputation: 27609

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

Upvotes: 10

Related Questions