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[0] = a[0] - 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 [0] = a [0] - 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.

+3


source to share


1 answer


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 a

, is that if you change it, you may end up changing the list you have already added to b

. One way to work around this problem is to always create a new copy a

whenever you want to change it.

import copy

b = []

a = [1,8,10]
b.append(a)

a2 = copy.deepcopy(a)  
a2[0] = a2[0] - 1
b.append(a2)

print(b)

      

Another way could be to make a copy a

whenever you add it to b

, so that you don't need to create new variables:



import copy

b = []

a = [1,8,10]
b.append(copy.deepcopy(a))

a[0] = a[0] - 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 b

. This means that whenever you change a

, it looks like you changed everything in b

.

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 b

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[:]

. a[:]

tells Python to get a slice of the list a

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.

+3


source







All Articles