1

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?

Nutabella
  • 13
  • 5

2 Answers2

1

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.

Jarvis
  • 8,494
  • 3
  • 27
  • 58
0

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.

samnodier
  • 355
  • 3
  • 2
  • This is incorrect. `new_list = list_[:]` will still change the elements inside the nested lists if any one of them is changed. – Jarvis Dec 29 '20 at 07:12