I've looked into swapping elements in lists on this site but most cases deal with swapping one element with another.
Here I am trying to swap the position of slices of unequal length. For an example list:
x = [6,2,4,3,4,1,4,5]
I was hoping for an elegant way used to swap values in lists and variables in general such as the form below:
x[0:1], x[1:7] = x[1:7], x[0:1]
#Expected output
x = [2, 4, 3, 4, 1, 4, 5, 6]
Unsurprisingly it doesn't work, it swaps the first two elements:
#Actual output
x = [2, 6, 4, 3, 4, 1, 4, 5]
Another example: Swap x[0:4]
with x[5:7]
:
#Expected output
x = [1, 4, 4, 6, 2, 4, 3, 5]
I hope it's clear that the swapping is such that the first element of the slice1
occupies the previous location of the first element of slice2
. The rest follows.
Is there a simple way to do this elegantly and efficiently?
You can use collections.deque
to rotate the values:
import collections
x = [6,2,4,3,4,1,4,5]
d = collections.deque(x)
d.rotate(-1)
print(d)
Output:
[2, 4, 3, 4, 1, 4, 5, 6]
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