-2

I have a list that i want to compare to after it gets modified. The previous_list = current_list followed by a modification to the current_list. But the issue i have is anytime the current_list is updated, the previous_list is also updated because everything in python is a reference. Ive tried,

previous_list = current_list[:]
previous_list = current_list.copy()
previous_list = list(current_list)

but none of these work, every time current_list is updated the previous list is updated immediately without reading this line,

previous_list = current_list[:] 

again.

My goal is to have a while loop the runs until the list are equal. Each loop the current_list is modified after the previous_list is updated with the current_value. I thought the solution was using one of the copy methods above to create a copy of the list and assign but maybe that is a reference too then.

John
  • 1
  • 1
  • 2
  • 2
    The word for this kind of copy is 'clone'. Clones come in two kinds: shallow and deep. – jarmod Feb 28 '20 at 23:56
  • The list (the container, not the values) is indeed copied, but the items are not, they are shared by the two lists. This is known as a shallow copy. try `previous_list = copy.deepcopy(current_list)` – flakes Feb 29 '20 at 00:01
  • This *list is being copied*. Whatever is inside the list isnt, though, since these are all shallow copies. You need a deep copy. Maybe simply `previous = [x.copy() for x in current]` – juanpa.arrivillaga Feb 29 '20 at 00:02
  • Can you try sharing your code? – Errol Feb 29 '20 at 00:06
  • Yes that worked! thank you @flakes – John Feb 29 '20 at 00:07

2 Answers2

0
l = [1,2,3]

l2 = list(l)

id(l)
2860467931976

id(l2)
2860467932424
Mark Snyder
  • 1,635
  • 3
  • 12
0

This list is being copied. Whatever is inside the list isnt, though, since these are all shallow copies. You need a deep copy. Maybe simply previous = [x.copy() for x in current] – juanpa.arrivillaga

John
  • 1
  • 1
  • 2