0

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, '_'], ['_', '_', '_']]
>>> 
  • 1
    When you create lists with `*`, the returned lists refer to the same object, whereas they are created independently in your list comprehension. You can verify this with `a[0] is a[1]` and `arr[0] is arr[1]` – sacuL Jul 08 '18 at 13:31

1 Answers1

0

When you use solution 1 and 2, you actually create 3 pointers to the same list. This is equivalent to:

a = ['_']
b = a

If you modify a or b, the result will be the same.

Dric512
  • 3,525
  • 1
  • 20
  • 27