Rotate List

Rotate a list by K positions to the right.

PythonBeginner
Python
# Program to rotate a list by K positions

items = input("Enter list elements separated by space: ").split()
K = int(input("Enter rotation step K: "))

n = len(items)
if n == 0:
    rotated = []
else:
    K = K % n
    rotated = items[-K:] + items[:-K]

print("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']

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