Home > Net >  nested array index python
nested array index python

Time:11-30

scores = [[0,0]]*10
scores[1][1]  = 1
print(scores)
>>[[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]

I want to increment at a specific position in a nested list in python, but am incrementing the entire list instead. Can anyone explain this behavior?

CodePudding user response:

This is because python is first creating the list, then is creating the reference ten times. In other words, using this method only one list is created. Try this:

scores = []
for i in range(10):
    scores.append([0, 0])
scores[1][1]  = 1
print(scores)

Output:

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

CodePudding user response:

scores = [[0,0]]*10 makes 10 copy of the same objects. If you examine the id() of the list's elements, for example by id(scores[3]), you can see their references are the same. If you want to have different objects in your list, you should use something like: scores = [[0,0] for i in range(10)]

  • Related