What is the best (fastest/most pythonic) way to reverse a part of an array in-place?
E.g.,
def reverse_loop(l,a,b):
while a < b:
l[a],l[b] = l[b],l[a]
a += 1
b -= 1
now after
l = list(range(10))
reverse_loop(l,2,6)
l is [0, 1, 6, 5, 4, 3, 2, 7, 8, 9] as desired.
Alas, looping in Python is inefficient, so a better way is needed, e.g.,
def reverse_slice(l,a,b):
l[a:b+1] = l[b:a-1:-1]
and reverse_slice(l,2,6) restores l to its original value.
Alas, this does not work for the border cases: reverse_slice(l,0,6)
truncates l to [7, 8, 9] because l[a:-1:-1] should be l[a::-1].
So, what is The Right Way?