Search code examples
pythonlist-comprehension

python list comprehension: creating 2d array


Are these two expressions the same?

a = [[0]*3]*3
b = [[0]*3 for i in range(3)]

The resulting a and b values look the same. But would one way be better than the other? What is the difference here.


Solution

  • They're not the same

    >>> a[1][2] = 5
    >>> a
    >>> [[0, 0, 5], [0, 0, 5], [0, 0, 5]]
    
    
    >>> b[1][2] = 5
    >>> b
    >>> [[0, 0, 0], [0, 0, 5], [0, 0, 0]]
    

    The first one creates an outer array of pointers to a single inner array while the second actually creates 3 separate arrays.