6

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

4
  • are you open to using numpy? Commented Jul 30, 2017 at 22:32
  • So, what exactly do you mean by array? numpy.ndarray? Or array.array? Commented Jul 30, 2017 at 22:33
  • Please post a minimal example. What is the actual data type? docs.python.org/3/library/array.html? Commented Jul 30, 2017 at 22:33
  • An array.array. I am not averse to using NumPy. I'll update my original question; thank you. Commented Jul 30, 2017 at 22:36

2 Answers 2

8

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]])
Sign up to request clarification or add additional context in comments.

3 Comments

@tpepin96 yes, they are. Although, given the dimensions you are talking about, even an list of lists wouldn't be an issue on modern hardware.
@tpepin96 They are primitive arrays, so each element is whatever size the dtype implies...
@tpepin96 scipy.sparse exists for cases that are actually large (1000x1000 is not)
3

The numpy equivalent of the code you posted is:

import numpy as np
my_array = np.empty([height, width])

empty reserves uninitialized space, so it is slightly faster than zeros, because zeros has to make sure that everything is initially set to 0.

Note that, like in C/C++, you should write values before reading them, because they initially "contain garbage".

Docs:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html

https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.