Rotate List in Python
Rotate a list by K positions to the right.
BeginnerList ProgramsExample 15 of 25
rotate-list.py
Run in browser1# Program to rotate a list by K positions23items = input("Enter list elements separated by space: ").split()4K = int(input("Enter rotation step K: "))56n = len(items)7if n == 0:8 rotated = []9else:10 K = K % n11 rotated = items[-K:] + items[:-K]1213print("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.