Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Copy an `array.array`

Is there a way to copy an array.array (not a list) in Python, besides just creating a new one and copying values, or using .to_something and .from_something? I can't seem to find anything in the documentation. If not, is there a similar builtin datatype that can do this?

I am working on a high-performance module, so the faster the answer, the better.

My current solution is just using .to_bytes and .from_bytes, which is about 1.8 times faster from my tests.

like image 590
internet_user Avatar asked Dec 05 '25 14:12

internet_user


1 Answers

Not sure what your array.array includes, but using a sample:

>>> import array
>>> a = array.array('i', [1, 2, 3] * 1000)
array('i', [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1,
2, 3, 1, 2, 3, 1, 2, 3, 1, 2, ... ])

Some set up:

>>> from copy import deepcopy
>>> import numpy as np

Timing various methods

(using the %timeit magic in a Jupyter Notebook):

Slicing

In [1]: %timeit cp = a[:]

418 ns ± 4.89 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Deepcopy

In [2]: %timeit cp = deepcopy(a)

1.83 µs ± 34 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

numpy copy ... NOTE: This produces a numpy array, not an array.array

In [3]: %timeit cp = np.copy(a)

1.87 µs ± 62.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

List Comprehension and array.array conversion

In [4]: %timeit cp = array.array('i', [item for item in a])

147 µs ± 5.39 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

numpy copy and array.array conversion

In [5]: %timeit cp = array.array('i', np.copy(a))

310 µs ± 2.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Copying to an existing array

In[6]: pre = array.array('i', [0, 0, 0] * 1000)
In[7]: %timeit for i, element in enumerate(a): pre[i] = a[i]

344 µs ± 7.83 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
like image 98
E. Ducateme Avatar answered Dec 07 '25 03:12

E. Ducateme