Rotate List in Python

Rotate a list by K positions to the right.

BeginnerList ProgramsExample 15 of 25
rotate-list.py
Run in browser
1# Program to rotate a list by K positions
2
3items = input("Enter list elements separated by space: ").split()
4K = int(input("Enter rotation step K: "))
5
6n = len(items)
7if n == 0:
8 rotated = []
9else:
10 K = K % n
11 rotated = items[-K:] + items[:-K]
12
13print("Rotated list:", rotated)

Output

Enter list elements separated by space: 1 2 3 4 5
Enter rotation step K: 2
Rotated list: ['4', '5', '1', '2', '3']

What's going on

We use slicing to take the last K elements and move them to the front.