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)