mcu
mcu

Reputation: 3512

Python Typed Array of a Certain Size

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.

Upvotes: 2

Views: 3172

Answers (2)

autf
autf

Reputation: 13

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.

Upvotes: 0

nimrodm
nimrodm

Reputation: 23779

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.

Upvotes: 4

Related Questions