Search code examples
pythoncopypython-classvariable-initialization

Python: Making a distinct copy of each class object in a list


How do I make a copy of a list of objects in a Python class such that each of the copies is a distinct instance of said Python class?


Suppose I have a Python class

class myClass():
    def __init__(self, neighbor):
        self.neighbor = neighbor

Additionally suppose myList = [a,b,c,d,...] is a list of myClass objects such that each entry in myList has another entry in myList populating its neighbor attribute. For example, maybe

a.neighbor = b
b.neighbor = c
etc.

I want to make a copy of myList whose entries are new myClass objects (they have to be different objects), but have directly comparable myClass data.

Concretely (and naively) I would like a function that returns newList = [a0,b0,c0,d0,...] with

a0.neighbor = b0
b0.neighbor = c0
etc.

If I can implement the operation in the parentheses below I get what I want.

def myFunction(myList):
    myDict = {}
    newList = []
    for item in myList:
        
        (create a myClass object called item0)
        newList = newList.append(item0)
        
        myDict{item} = item0

# populate the neighbor data for each new item
    for item in myList
        myDict{item}.neighbor = myDict{item.neighbor}
        
    return newList

How can I implement the procedure described in the parentheses?


Solution

  • I would suggest using the copy.deepcopy() function.