+3 votes
in Programming Languages by (56.5k points)
I want to shift all elements of a Python list to the right by one position and make the last element the first element. How can I do this in a Pythonic way?

1 Answer

+2 votes
by (73.8k points)
selected by
 
Best answer

Although you want to shift the list elements to the right, you can do this by decreasing their current indices by 1. Thus, the last element will become the first element, and all other elements will be shifted to the right.

Here is an example:

>>> a=[1,2,3,4,5]
>>> [a[i-1] for i in range(len(a))]
[5, 1, 2, 3, 4]
 


...