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.
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, ... ])
>>> from copy import deepcopy
>>> import numpy as np
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With