How to modify element in a list from a list of lists

Viewed 32

I have a list of 4 integer lists, each with 4 elements.

How can I modify an element in a particular list without modifying all other elements of the same index number in the other 3 lists?

What I've been trying to do, for example, is modifying the first list at the first position through the following code:

longList[0][0] = 1

What I end up getting is a list that looks like

[[1,0,0,0], [1,0,0,0], [1,0,0,0], [1,0,0,0]]

rather than what I want:

[[1,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]]

which is strange, considering that I only asked for the first element in the first list to be modified.

Would anyone know a way to fix this issue so that I can get the latter result rather than the former one, which my code is outputting?

Maybe it's a problem in the way I've been setting up the list? (which is as follows):

longList = [[0] * 4] * 4

Here's the most simplified version of my code issue:

longList = [[0] * 4] * 27

print(longList)
longList[0][1] = 1
print(longList)  #outputs the result I don't want

Thanks.

1 Answers

Please check this out

longList = [[0] * 4] * 4
tmp = longList[0].copy()
tmp[0] = 1
longList[0] = tmp
print(longList)
Related