Create 2D array in Python

I used to create 2D zero array by the following way, for example:

arr = [[0] * 3] * 4

However, `arr` actually references the list [0,0,0] 4 times. If you set `arr[1][1] = 5`, for example, you will find all “other” lists in `arr` have 5 then.

>>> arr[1][1] = 5
>>> arr
[[0, 5, 0], [0, 5, 0], [0, 5, 0], [0, 5, 0]]

 

Therefore, the best way to create a 2D array is either using `numpy` or:

arr = [[0]*3 for i in range(4)]

 

Reference

http://stackoverflow.com/a/6667529/1758727

Leave a comment

Your email address will not be published. Required fields are marked *