I am using Python 3 and am trying to create 2D integer arrays of a known and fixed size. How can I do this?
The arrays I have in mind are the Python-provided array.array
, although I am not averse to using a library like NumPy.
I know this can be done via lists, but I want to use an array since they are much more space efficient. Right now, I am initializing lists in this way, but I want to replace it with an array:
my_list = [[ 0 for _ in range(height) ] for _ in range(.width)]
For example, in C, I would write
int my_array[ width ][ height ];
How can I do this in Python
To initialize an array in Python, use the numpy. empty() function. The numpy. empty() function creates an array of a specified size with a default value = “None“.
We can declare a two-dimensional integer array say 'x' of size 10,20 as: int x[10][20]; Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the row number and 'j' is the column number.
Use len() to find the length of a 2D list in Python. Call len(obj) with a 2D list as obj to get the number of rows in the array. Call len(obj) with a list row as obj to get the number of columns. Multiply the number of rows by that of columns to get the total length of the list.
You can use numpy:
import numpy as np
my_array = np.zeros([height, width])
For example:
>>> np.zeros([3, 5])
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
Note that if you specifically need integers, you should use the dtype
argument
>>> np.zeros([3, 5], dtype=int)
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With