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…

Read the entire article at the source link… Tamim Shahriar

#codango #developer #development #coder #coding

We're happy to share this resource that we found. The content displayed on this page is property of it's original author and/or their organization.

 

Leave a Reply

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

*