2

This will create an empty array of type signed int:

import array
a = array.array('i')

What is an efficient (performance-wise) way to specify the array lengh (as well as the array's rank - number of dimensions)?

I understand that NumPy allows to specify array size at creation, but can it be done in standard Python?

Initialising an array of fixed size in python
This deals mostly with lists, as well as no consideration is given to performance. The main reason to use an array instead of a list is performance.

2
  • possible duplicate of Initialising an array of fixed size in python Commented Aug 22, 2015 at 18:33
  • @sobolevn Which of those answers applies to my question? Commented Aug 22, 2015 at 18:35

2 Answers 2

4

The array constructor accepts as a 2nd argument an iterable. So, the following works to efficiently create and initialize the array to 0..N-1:

x = array.array('i', range(N))

This does not create a separate N element vector or list.

(If using python 2, use xrange instead). Of course, if you need different initialization you may use generator object instead of range. For example, you can use generator expressions to fill the array with zeros:

a=array.array('i',(0 for i in range(N)))

Python has no 2D (or higher) array. You have to construct one from a list of 1D arrays.

The truth is, if you are looking for a high performance implementation, you should probably use Numpy.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This is what I am looking for. Do you know how to do a generator version to initialize to zeros? Can this be done for 2D or 3D arrays?
0

It's simple and fast to just use:

array.array('i', [0]) * n

Timing of different ways to initialize an array in my machine:

n = 10 ** 7
array('i', [0]) * n     #  21.9 ms
array('i', [0]*n)       # 395.2 ms
array('i', range(n))    # 810.6 ms
array('i', (0 for _ in range(n)))  # 1238.6 ms

You said

The main reason to use an array instead of a list is performance.

Surely arrays use less memory than lists.

But by my experiment, I found no evidence that an array is always faster than a normal list.

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.