[Math][Python] Shift array using modulo arithmetic or remainder operation

The following piece of code shifts an input array left or right by $shift$ items.

This is the same operation that ROR/ROL x86/x64 instructions do.

Thanks to modulo arithmetic, we can use the remainder operation to make our code tidy and concise. Remainder operation here returns array iterator/pointer back, if it goes over array's bound during execution.

#!/usr/bin/env python3

def reverse_left(input, shift):
    input_len=len(input)
    output=[None for i in range(input_len)]

    for i in range(input_len):
        output[i]=input[(i+shift) % input_len]

    return output

def reverse_right(input, shift):
    input_len=len(input)
    output=[None for i in range(input_len)]

    for i in range(input_len):
        output[(i+shift) % input_len]=input[i]

    return output

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

print (reverse_left(test, 3))
print (reverse_right(test, 3))
Output:
[4, 5, 6, 7, 8, 9, 1, 2, 3]
[7, 8, 9, 1, 2, 3, 4, 5, 6]

Can you find more concise code for that operation? (The loop body, of course.)

More information about modulo arithmetic you can find in my Mathematical recipes book.

P.S. There are RotateLeft and RotateRight in Wolfram Mathematica, that do the same.

UPD: comment(s) at reddit.


List of my other blog posts.

Yes, I know about these lousy Disqus ads. Please use adblocker. I would consider to subscribe to 'pro' version of Disqus if the signal/noise ratio in comments would be good enough.