Python math index variable list
This works the way I want
a = [1,8,10] b = list([a]) a = [0,8,10] b.append(a) a = [0,0,10] b.append(a) print(b)
will give me the list I want:
[[1, 8, 10], [0, 8, 10], [0, 0, 10]]
I need to change values with variables based on the index of a list like this
a = [1,8,10] b = list([a]) a = a - 1 b.append(a) print(b)
and I get this result:
[[0, 8, 10], [0, 8, 10]]
My whole task is to track my actions to create the nim game. I think I can see how setting  = a  - 1 changes the value in both places, even when I tried to use a deep copy, but I'm stumped on how else to get the answer. I'm sure this is obvious, but I don't know what keywords to use to find a solution, so please help me.
source to share
Using deepcopy should work - I suspect you were using it in the wrong place.
The danger of using a single list as a template, as you did with
, is that if you change it, you may end up changing the list you have already added to
. One way to work around this problem is to always create a new copy
whenever you want to change it.
import copy b =  a = [1,8,10] b.append(a) a2 = copy.deepcopy(a) a2 = a2 - 1 b.append(a2) print(b)
Another way could be to make a copy
whenever you add it to
, so that you don't need to create new variables:
import copy b =  a = [1,8,10] b.append(copy.deepcopy(a)) a = a - 1 b.append(copy.deepcopy(a)) print(b)
The common point between these two different approaches is that we always add any given list exactly once. In your code, you add the same list multiple times to
. This means that whenever you change
, it looks like you changed everything in
In the two examples I have given, I only add the list once and copy it if I need to make changes. By doing this, I ensure that each list inside
is unique and does not run into the problem you are facing.
As a side note, another way to create a copy of the list is
a2 = a[:]
tells Python to get a slice of the list
from the beginning of the list to the end, essentially copying it. Please note that this is a shallow copy, not a deep copy. However, since your lists only contain numbers, the shallow copy should work fine.
source to share