Python: Copy an ‘array.array’ … here is a solution to the problem.
Python: Copy an ‘array.array’
Is there a way to copy array.array
(not list
) in Python, Instead of creating a new list and copying the values, do you use .to_something
and .from_something
? I can’t seem to find anything in the docs. If not, is there a similar built-in data type that can do that?
I’m working on a high-performance module, so the sooner the answer, the better.
My current solution is just using .to_bytes
and .from_bytes
, which is about 1.8x faster than my tests.
Solution
Not sure what your array.array
contains, but use example:
>>> 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 settings:
>>> from copy import deepcopy
>>> import numpy as np
Various methods of timing
(Use %timeit magic in Jupyter Notebook
):
Slice
In [1]: %timeit cp = a[:]
418 ns ± 4.89 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Deep copy
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 generates a numpy array instead of 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 understanding 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 replication 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)
Copy 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)