0

I have a list of lists and I want to assign to the first element of each list a value in order from 0 to 3. I wrote the following code:

var = [[-1] * 5] * 4
for i in range(4):
    var[i][0] = i+1
print(var)

The output is

[[4,-1,-1,-1,-1],
[4,-1,-1,-1,-1],
[4,-1,-1,-1,-1],
[4,-1,-1,-1,-1]]

But it should be:

[[1,-1,-1,-1,-1],
[2,-1,-1,-1,-1],
[3,-1,-1,-1,-1],
[4,-1,-1,-1,-1]]

How do I do it?

Paul Erlenmeyer
  • 523
  • 2
  • 6
  • 29
  • 1
    When you crated `var`, you have a same list 4 times. "The same" meaning, when you change one, you change them all. It is like having a list in row 0, and then mirrors for the rest of the rows. – James Mar 14 '20 at 13:52
  • @James Alright, thanks! That was quite unexpected ... – Paul Erlenmeyer Mar 14 '20 at 14:10

0 Answers0