Apr-07-2021, 06:57 PM
(Apr-07-2021, 06:33 PM)deanhystad Wrote: You need to do a deep copy
import copy a = [[1, 1], [2, 2]] b = a.copy() print('Copy') for x, y in zip(a, b): print(x, y, id(x), id(y)) print('\nDeep Copy') b = copy.deepcopy(a) for x, y in zip(a, b): print(x, y, id(x), id(y))When you copy a list of lists the copy is a new list that contains lists from the original. To create copies of the contents you should use deepcopy from the copy library. Notice that the object ID's match when doing b = a.copy(), but when doing b = copy.deepcopy(a), new lists are created for the copy.
Output:Copy [1, 1] [1, 1] 2858215123584 2858215123584 [2, 2] [2, 2] 2858215123072 2858215123072 Deep Copy [1, 1] [1, 1] 2858215123584 2858215122240 [2, 2] [2, 2] 2858215123072 2858215123520
Thanks pal, you've solved my problem and taught me a lesson.