Reputation: 431
Suppose I have two lists in python:
>>> x
[0, 1, 2, 3, 4, 5]
>>> y
[0, -1, -2, -3, -4, -5]
Suppose I want to swap elements of the arrays from some index until the end. So if, for example, I let the index=3, then I want the following:
>>> x
[0, 1, 2, -3, -4, -5]
>>> y
[0, -1, -2, 3, 4, 5]
This is easy to do:
>>> tempx=x[:3]+y[3:]
>>> tempx
[0, 1, 2, -3, -4, -5]
>>> tempy=y[:3]+x[3:]
>>> tempx
[0, 1, 2, -3, -4, -5]
>>> tempy
[0, -1, -2, 3, 4, 5]
>>> x=tempx
>>> y=tempy
>>> x
[0, 1, 2, -3, -4, -5]
>>> y
[0, -1, -2, 3, 4, 5]
But if x and y are numpy arrays, this doesn't work.
>>> x=[0,1, 2, 3, 4, 5]
>>> y=[0,-1,-2,-3,-4,-5]
>>> import numpy as np
>>> x=np.array(x)
>>> y=np.array(y)
>>> x
array([0, 1, 2, 3, 4, 5])
>>> y
array([ 0, -1, -2, -3, -4, -5])
>>> tempy=y[:3]+x[3:]
>>> tempy
array([3, 3, 3])
>>> tempy=[y[:3],+x[3:]]
>>> tempy
[array([ 0, -1, -2]), array([3, 4, 5])]
>>> tempy=(y[:3],+x[3:])
>>> tempy
(array([ 0, -1, -2]), array([3, 4, 5]))
How do I get the following?
>>> tempx
array([0, 1, 2, -3, -4, -5])
>>> tempy
array([0, -1, -2, 3, 4, 5])
Upvotes: 1
Views: 621
Reputation: 11691
Swapping list slices is easier than you think.
x = [1,2,3]
y = [11,22,33]
x[1:], y[1:] = y[1:], x[1:]
>>> x
[1, 22, 33]
>>> y
[11, 2, 3]
This doesn't work in numpy because basic slices are views, not copies. You can still make an explicit copy if you want though.
x = np.array(range(6))
y = -np.array(range(6))
temp = x[3:].copy()
x[3:] = y[3:]
y[3:] = temp
And, if you think about the order of operations carefully, you can still do this in one line without an explicit temp variable.
x[3:], y[3:] = y[3:], x[3:].copy()
Either way, we get
>>> x
array([ 0, 1, 2, -3, -4, -5])
>>> y
array([ 0, -1, -2, 3, 4, 5])
Upvotes: 2