Search code examples
pythonarrayspython-3.xreversein-place

Reverse a slice of an array in-place


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?


Solution

  • How about this?

    def reverse_slice(l, a, b):
        l[a:b] = l[a:b][::-1]
    
    l = list(range(10))
    reverse_slice(l, 0, 6)  # excludes l[6]
    print(l)
    

    Output:

    [5, 4, 3, 2, 1, 0, 6, 7, 8, 9]
    

    An alternative with the inbuilt function reversed:

    def reverse_func(l, a, b):
        l[a:b] = reversed(l[a:b])
    

    In my tests, slicing is faster than using reversed by a factor of 1.2x-1.5x.