Follow-up question of: Python swap indexes using slices
r = [\'1\', \'2\', \'3\', \'4\', \'5\', \'6\', \'7\', \'8\']
If I want to swap sli
Without any calculation, you can do :
def swap(r,a,b,c,d):
assert a<=b<=c<=d
r[a:d]=r[c:d]+r[b:c]+r[a:b]
An interesting (but silly one, the one by B. M. is clearly better) solution would be to create an object that supports slicing:
class _Swapper(object):
def __init__(self, li):
self.list = li
def __getitem__(self, item):
x = list(item)
assert len(x) == 2 and all(isinstance(i) for i in x)
self.list[x[0]], self.list[x[1]] = self.list[x[1]], self.list[x[0]]
def swap(li):
return _Swapper(li)
swap(r)[a:b, c:d]