I donโt think there is any elegant, completely general way. Here's a not-so-elegant way:
def swapslices(l, from1, to1, from2, to2): if not (from1 <= to1 <= from2 <= to2): raise ValueError('slices out of order or overlapping') if to1 - from1 == to2 - from2:
This function requires you to go through the bottom slice first and not try to use slices, like 6:3 .
The function relies on the fact that if you try to replace fragments a and c here:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ---- ---- ------- abc
this is equivalent to replacing the whole section a + b + c with c + b + a :
[0, 5, 6, 7, 3, 4, 1, 2, 8, 9] ------- ---- ---- cba
Example:
>>> l = list(range(10)) >>> swapslices(l, 1, 3, 5, 8) >>> l [0, 5, 6, 7, 3, 4, 1, 2, 8, 9]