Python binary array

How to create a large array in python, how to create this efficiently

in C / C ++:

byte *data = (byte*)memalloc(10000); 

or

 byte *data = new byte[10000]; 

in python ...?

+4
source share
4 answers

Look at the array module :

 import array array.array('B', [0] * 10000) 

Instead of passing a list to initialize it, you can pass a generator that is more memory efficient.

+7
source

You can pre-select the list with:

 l = [0] * 10000 

which will be slightly faster than replaced by it (as it avoids intermediate redistributions). However, this usually allocates space for a list of pointers to whole objects that will be larger than an array of bytes in C.

If you need memory efficiency, you can use an array object. i.e:

 import array, itertools a = array.array('b', itertools.repeat(0, 10000)) 

Please note that this can be somewhat slower to use in practice, since when accessing elements, the unboxing process occurs (they must first be converted to a python int object).

+6
source

Usually with python you just create a list

 mylist = [] 

and use it as an array. Alternatively, I think you can look for an array module. See http://docs.python.org/library/array.html .

0
source

You can efficiently create a large array using the array module, but using it will not be as fast as C. If you intend to do some math, you will be better off with numpy.array

Check this question for comparison.

0
source

All Articles