Nutabella
Nutabella

Reputation: 13

How can I copy a Python object with its values not its references addresses of variables?

So, I have a Python list like this:

list_ = [[Object, 2, ["r","g","b"]],
         [Object, 5, ["r","g","b"]],
         ...
         [Object, 3, ["r","g","b"]]]

I need to copy this list to a new list but when I use copy.deepcopy() it takes the list with its references.

new_list = copy.deepcopy(list_)

When I change a value in new_list, it affects the values in the list_ I want to copy the list_ that the new_list will have independent variables, so it must copy values, not reference addresses of variables. How can I do that?

Upvotes: 1

Views: 99

Answers (2)

samnodier
samnodier

Reputation: 395

I don't know what's happening with your code but when I perform

new_list = copy.deepcopy(list_)

The code works perfectly fine. I changed the values in the new_list and list_ wasn't affected. The problem with your code might be somewhere else. Please go through your code and check that.

The other way you can use to copy items from one list into another is list comprehension

list_ = [[Object, 2, ["r","g","b"]],
         [Object, 5, ["r","g","b"]],
         ...
         [Object, 3, ["r","g","b"]]]


new_list = list_[:]

Hopefully this can work for you.

Upvotes: 0

Jarvis
Jarvis

Reputation: 8564

Just use list comprehension:

new_list = [x[:] for x in list_]

But to be honest, copy.deepcopy would work correctly regardless of the dimensions inside your list, you must be making a mistake somewhere else. Regardless, it can be incredibly slow as compared to list slicing.

Upvotes: 1

Related Questions