Python move all elements of a list to the right by one

pythonpython-3.x

So I want to move all the elements to the right so for example if I had a list of [1, 2, 3, 4, 5] it would become [5, 1, 2, 3, 4]. So basically the rightmost element wraps around to the leftmost element and the other elements basically shift the right.

Here is my code:

length = len(values)
old_right = values[length - 1]
for j in range(length - 1, 0, -1):
    values[j] = values[j - 1]
values[0] = old_right

When i enter it in idle i get an error on the last line on values[0] (highlighted on values) saying SyntaxError: invalid syntax. I do not know why I get this error.

Also, how would I have to change my code to make it go from [5, 4, 3, 2, 1] back to [1, 2, 3, 4, 5], i.e. reverse the process?

Best Answer

>>> lst = [1, 2, 3, 4, 5]
>>> [lst[-1]] + lst[:-1]
[5, 1, 2, 3, 4]

reverse:

>>> lst = [5, 1, 2, 3, 4]
>>> lst[1:] + [lst[0]]
[1, 2, 3, 4, 5]

edit:

I used [1, 2, 3, 4, 5] as an example, but i wrote the code for it to work on any list no matter what it is it would take the rightmost value of the list to the left. In your case this does work but only if you assign the specific list. I am wondering how would you do it so it works any general case.

Then write a function.

def shift_right(lst):
    try:
        return [lst[-1]] + lst[:-1]
    except IndexError:
        return lst