Does Python have anything like Java's System.arraycopy? I don't want to just copy the reference (shallow copy) nor do I want to slice it (deep copy w/new ref). I want to keep the target's reference (as I have multiple variables pointing to the same list) and copy the individual cells from the source to the target. Exactly like Java's arraycopy. So far the only way I can find to do this in Python is to write my own. In Java it is more performant to use System.arraycopy than rolling your own, not sure if that is the case in Python.
If I follow the described behavior, slice assignment is the Pythonic way to do this:
foo = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
bar = foo
baz = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
foo[0:4] = baz[0:4]
>>> foo
[10, 9, 8, 7, 4, 5, 6, 7, 8, 9]
>>> bar
[10, 9, 8, 7, 4, 5, 6, 7, 8, 9]
If the source contains object references, that will assign references to the same objects into the destination - if you want to deep copy the source data I think you'd have to do something like:
foo[0:4] = [copy.deepcopy(x) for x in baz[0:4]]
Update: Peter DeGlopper's method is way better. Go for that one.
Sorry, this is the best you get:
def arrayCopy(src, srcPos, dest, destPos, length):
for i in range(length):
dest[i + destPos] = src[i + srcPos]
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