Value Changes In New List Impact Previous List Values, Within A List Of Lists
Solution 1:
The short answer to your question is using colon:
combinations.append(combinations[0][:])
Why? The reason is that in python when you append a variable into your list, the variable is appended by its reference. In your example, it means that the two elements in the list are the same. They are pointing to the same address in the memory and if you modify either of them, both value will change as they are one and using the same chunk of memory.
If you want to copy the values of a variable, in your case, combinations[0], you need to use colons to make a copy of values and put them in another part of memory (it will occupy another chunk of memory with different address) In this case, you can modify them separately.
You can also take a look at this question and answer: python list by value not by reference
I hope this helps.
Solution 2:
use
combinations.append(list(combinations[0]))
to append a copy of the first element.
Post a Comment for "Value Changes In New List Impact Previous List Values, Within A List Of Lists"