Rotate List
Rotate a list by K positions to the right.
BeginnerTopic: List Programs
Python Rotate List Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# 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']
Understanding Rotate List
We use slicing to take the last K elements and move them to the front.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.