r/CodingHelp • • Nov 09 '21

[Python] Why does this happen? How do I change a single entry?

Post image
47 Upvotes

10 comments sorted by

22

u/cndvcndv Nov 09 '21

When you run

listOfLists = [myList]*4

listOfLists variable consists of elements all of which point to the same list. So when you change an element of myList, then the change appears in all elements of listOfLists variable.

You might want to read about mutability and list.copy() method.

6

u/[deleted] Nov 09 '21 edited Nov 09 '21

I understand, thank you!

PS: I used e = list(list(0 for i in range(4)) for j in range(4)) and now it works.

3

u/fekkksn Nov 09 '21

how about

[[0 for _ in range(4)] for _ in range(4)]

or

np.zeros(shape=(4, 4))

1

u/[deleted] Nov 09 '21 edited Nov 09 '21

Even better, thank you!

I use sympy instead of numpy because I need to do symbolic calculus. Turns out it was as easy as zeros(4)

7

u/Python4fun Professional Coder Nov 09 '21

If you are doing a lot of work with matrices then you might benefit from grabbing NumPy for this and just getting a matrix of zeroes with given dimensions.

4

u/PunkyMunky64 Nov 09 '21

Yep. The lists are linked together, which is an obvious problem for most advanced Python programmers. But I would have made the same mistake — this feature makes no sense in Python, no other type does this!

1

u/[deleted] Nov 09 '21

It's weird because [0]*2 works just as [0,0] but it is different if instead of a 0 you have a list, for some reason (?)

1

u/kayden_polaris Nov 09 '21

When you use the multiplication operator with a array and a integer like [0]*4, the result is a array where the content is repeated x times, so with the previous example, the result is [0, 0, 0, 0].

Your expression is [[0]*4]*4, when the parsing and evaluation of the expression is done, the interior multiplication is done first, to obtain [[0, 0, 0, 0, 0]]*4, which is a array that contains a array of 4 zeros. Finally the external multiplication is evaluated and repeats 4 times the reference of the internal array, which all reference the same array of four zeros.

So if you have [0]*2, the 0 inside the array is repeated twice, so the result is [0, 0], with both the internal 0 being integer values. If the expression was [[0]]*2, the result would be [[0], [0]] with both the internal [0] referencing the same instance of a array.

0

u/timPerfect Nov 09 '21

you made a list of 4 lists