1

I am trying the following steps (to copy a list of list, and to change the last item of each list)

list_weight=[['B', 'A', 5], ['B', 'D', 1], ['B', 'G', 2], ['A', 'B', 5], ['A', 'D', 3], ['A', 'E', 12], ['A', 'F', 5], ['D', 'B', 1], ['D', 'G', 1], ['D', 'E', 1], ['D', 'A', 3], ['G', 'B', 2], ['G', 'D', 1], ['G', 'C', 2], ['C', 'G', 2], ['C', 'E', 1], ['C', 'F', 16], ['E', 'A', 12], ['E', 'D', 1], ['E', 'C', 1], ['E', 'F', 2], ['F', 'A', 5], ['F', 'E', 2], ['F', 'C', 16]]
list_time = [i for i in list_weight]
for i in list_time:
    i[-1]=dt(2021,6,15,random.randint(0, 23))

print(list_time==list_weight)

Finally, I obtain that list_time is equal to list_weight and I don't know why. I have tried to use .copy method or list_time = list_weight[:] but they don't work.

Thank you

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
andriuu99
  • 29
  • 5

2 Answers2

3

Elements of list_weights are themselves lists, and so you need to do a deepcopy:

list_time = [i[:] for i in list_weight]

Alternatively, using copy.deepcopy:

from copy import deepcopy

list_time = deepcopy(list_weight)
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

This is related to deep copy and shallow copy.

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

When you assign a list to a new variable, instead of creating a new list a reference to the same list is created. The variable points to the same list and if you change any variable pointing to the list, the list will be changed.

You can read the details at the link: https://docs.python.org/3/library/copy.html

Atif Bashir
  • 319
  • 4
  • 13