Issue
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.
Solution
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]]
Answered By - Peter DeGlopper
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.