Create 2D Array using List in Python

If for some reason you want to create a two dimensional array in Python and don't want to use external packages like numpy etc., the most obvious thing is to write a code like this :

>>> n = 3
>>> m = 4
>>> ara = [[0] * m] * n
>>> ara
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

But there is a problem. Check the code below-

>>> ara[0][0] = 1
>>> ara
[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]

Actually, when you do [0] * m, it returns a reference to a list and when you multiply it with n, the same reference is duplicated. Hence you see the change in a way that you didn't expect.

The right way to do it is to append [0] * m, n times in the array. You can code it in multiple ways. My preferred way is:

>>> ara = [[0] * m for _ in range(n)]

Comments

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code