I am given a list a = [1, 0, 0, 1, 0]
What I want to do now is to define a function that takes as input a list a
and s
, where s
is the number of positions I want to shift every entry of the list to the right. The rightmost entry will be shifted to the beginning of the list.
This means, the function shift(a, 2)
should return r = [1, 0, 1, 0, 0]
I am given a solution, which I do not understand:
def shift(a, s):
r = []
for i in range(len(a)):
r.append(a[(i-s) % len(a)])
return r
First question: Although we are shifting to the right, we are subtracting the number of shifts s
.
Second question: What is the purpose of the modulo operator?
Can somebody pls explain this to me at beginners level?