0

This is baffling me, two lists are changing in parallel even though the second isn't being touched.

I searched and found I should be using list comprehension to get a new pointer and thus I won't be working with the same list, but NAY it still does the below! I can't find a reason for this behaviour online.

display_order = current_order[:]
print(current_order)
print(display_order)
display_order[0][3] = "CHANGE"
print(current_order)
print(display_order)

Output:

[['ID', 'Product', '999', 'Section', 'Seat']]
[['ID', 'Product', '999', 'Section', 'Seat']]
[['ID', 'Product', '999', 'CHANGE', 'Seat']]
[['ID', 'Product', '999', 'CHANGE', 'Seat']]
Fraser Langton
  • 471
  • 3
  • 12
  • 2
    You copy the contents of the outer list, which is (the same) inner list. You would need a deep copy. – Christian König Mar 06 '19 at 10:05
  • Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – Christian König Mar 06 '19 at 10:06
  • 3
    Possible duplicate of [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Thierry Lathuille Mar 06 '19 at 10:06
  • List contains objects and you need to copy them. Use: `copy.deepcopy(current_order)`. – Austin Mar 06 '19 at 10:10

1 Answers1

0

The issue is that both variables point to the same inner list in the memory. When you do

display_order = current_order[:]

you get that situation in the memory:

display order -----> [['ID', 'Product', '999', 'Section', 'Seat']]
                      ^
                      |
current_order ---------

They both point to the same list.

You can avoid that situation with a deep copy of the list which will copy the values of the first list to the new location in memory. Replace the mentioned line with this line:

display_order = copy.deepcopy(current_order)
Primoz
  • 1,324
  • 2
  • 16
  • 34