I created list of lists in python by 3 methods. When I changed any element of list, All corresponding elements of each row were changed by using method 1 and 2 for list creation. What is actually happening in method 1 and 2?
method 1:
>>> a = [['_']*3]*3
>>> a
[['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
>>> a[1][1] = 1
>>> a
[['_', 1, '_'], ['_', 1, '_'], ['_', 1, '_']]
method 2:
>>> row = ['_']*3
>>> board = []
>>> for i in range (3):
... board.append(row)
...
>>> board
[['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
>>> board[1][1] = 1
>>> board
[['_', 1, '_'], ['_', 1, '_'], ['_', 1, '_']]
while doing with list comprehension works:
>>> arr = [['_' for i in range(3)] for i in range(3)]
>>> arr
[['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
>>> arr[1][1] = 1
>>> arr
[['_', '_', '_'], ['_', 1, '_'], ['_', '_', '_']]
>>>