Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant method for swapping unequal list slices? [duplicate]

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?

like image 470
Jer J Avatar asked Nov 07 '22 14:11

Jer J


1 Answers

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]
like image 125
Ajax1234 Avatar answered Nov 14 '22 21:11

Ajax1234