Python Create 2D Array utilizing Record in Python
If for some motive you wish to create a two dimensional array in Python and do not wish to use exterior packages like numpy and so on., the obvious factor is to write down a code like this :
1 2 3 4 5 | >>> n = three >>> m = four >>> ara = [[0] * m] * n >>> ara [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] |
However there’s a drawback. Verify the code below-
1 2 3 | >>> ara[0][0] = 1 >>> ara [[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]] |
1 |
Really, if you do [0] * m, it returns a reference to a listing and if you multiply it with n, the identical reference is duplicated. Therefore you see the change in a method that you just did not anticipate.
The proper method to do it’s to append [0] * m, n instances within the array. You’ll be able to code it in a number of methods. My most well-liked method is:
1 | >>> ara = [[0] * m for i in vary(n)] |