Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have anything like Java's System.arraycopy?

Tags:

java

python

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.

like image 892
JeffHeaton Avatar asked Dec 11 '22 09:12

JeffHeaton


2 Answers

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]]
like image 120
Peter DeGlopper Avatar answered Jan 22 '23 15:01

Peter DeGlopper


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]
like image 25
Thomas Ahle Avatar answered Jan 22 '23 14:01

Thomas Ahle