Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently initialize 2D array of size n*m in Python 3?

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

like image 572
lynn Avatar asked Jul 30 '17 22:07

lynn


People also ask

How do you initialize an array size 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“.

How do you declare the size of a 2D array?

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.

How do you print the size of a 2D array in Python?

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.


1 Answers

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]])
like image 149
Jonas Adler Avatar answered Oct 04 '22 16:10

Jonas Adler