Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list math index variable

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)

giving me the list that I want:

[[1, 8, 10], [0, 8, 10], [0, 0, 10]]

I need to change the values using variables based on the index of the 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 entire point is to keep track of my moves for creating the nim game. I think I see how setting a[0] = a[0] - 1 changes the value in both places even when I tried using deep copy but I am stumped on how else to get the answer. I am sure it is obvious but I don't know what key words to use to search for the solution, so please help me.

like image 243
JMJ Avatar asked Jun 23 '26 12:06

JMJ


1 Answers

Using deepcopy should work -- I suspect you were just using it in the wrong place.

The danger of using a single list as a template, as you were doing with a is that if you mutate it, you could end up changing the lists you've already appended to b. One way to get around this problem is to always create a new copy of 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 might be to make a copy of a whenever you append it to b, so that you don't have to keep creating 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 append any given list exactly once. In your code, you append the same list multiple times to b. That means that whenever you change a, it appears as if you changed everything in b.

In the two examples I provided, I append a list only once, and copy it if I need to make changes. By doing so, I ensure that each list inside b is unique, and avoid running into the issue you encountered.

As a side note, another way to create a copy of a list is to do a2 = a[:]. The a[:] is telling Python to get a list slice of a starting from the beginning of the list to the end, essentially copying it. Note that this is a shallow copy, not a deep copy. However, since your lists contain only numbers, a shallow copy should work fine.

like image 65
Michael0x2a Avatar answered Jun 26 '26 00:06

Michael0x2a



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!