1

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.

  • kindly share your code. I do same thing and i got `[[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]` – Mehmaam Sep 24 '22 at 05:16
  • @Mehmaam Sorry about that, I updated my answer with my code. – SeekNDestroy Sep 24 '22 at 05:20
  • 1
    Playing off of @NewEnglandcottontail 's comment, conisder the following: `ll = [[0] * 4] * 4; new_ll = [[0] * 4] * 4` => `ll[0] is ll[1]` will return True, versus `new_ll[0] is ll[0]` returns False, because new references are created. This also highlights the difference between `==` and `is`. – Shmack Sep 24 '22 at 05:31
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Mechanic Pig Sep 24 '22 at 05:52

1 Answers1

2

Please check this out

longList = [[0] * 4] * 4
tmp = longList[0].copy()
tmp[0] = 1
longList[0] = tmp
print(longList)
sourin_karmakar
  • 389
  • 3
  • 10
  • Thanks for the help! While your method works fine, it was an error in choosing to multiply the lists by a constant, as some other members kindly pointed out. – SeekNDestroy Sep 24 '22 at 05:38