Friday, August 18, 2017

Update a Python list - Don't know why this the case.

I was trying to update a list which contents a few lists. When I try to update a one element of a list within the list it seems updating all lists of the list. But it only happens when I create the list in the following way. I have no clue why this is the case.
example_list = [[0,0]]*3
print(example_list)

example_list[0][0] = 1
print(example_list)
print('')

example_list = [[0,0],[0,0],[0,0]]
print(example_list)

example_list[0][0] = 1
print(example_list)
[[0, 0], [0, 0], [0, 0]]
[[1, 0], [1, 0], [1, 0]]

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

1 comment:

  1. Finally, I have found out the reason. What is happening here is that when a list is created by multiplying (example_list = [[0,0]]*3) it doesn’t copy the list. It uses the same object 3 times. When we try to update the list, it is reflected across.

    ReplyDelete