Reputation: 3279
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.
Upvotes: 3
Views: 3364
Reputation: 12939
You don't need numpy to copy an array.array
object. And since array.array
objects can only contain ints, floats, or unicode characters, the concept of "shallow copy" and "deep copy" don't apply here.
You can just use the [:]
trick to make a copy of an array.array()
object:
>>> import array
>>> x = array.array('B', b'\xFF' * 10)
>>> x
array('B', [255, 255, 255, 255, 255, 255, 255, 255, 255, 255])
>>> y = x[:]
>>> y
array('B', [255, 255, 255, 255, 255, 255, 255, 255, 255, 255])
You can also pass it to the array.array()
initializer function.
For example:
>>> import array
>>> x = array.array('B', b'\xFF' * 10)
>>> x
array('B', [255, 255, 255, 255, 255, 255, 255, 255, 255, 255])
>>> y = array.array('B', x)
>>> y
array('B', [255, 255, 255, 255, 255, 255, 255, 255, 255, 255])
Be sure to pass the same "type code" (the 'B'
in the above example) for the new array.array
object.
Upvotes: 1
Reputation: 4248
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)
Upvotes: 5