Editor

Python Program to Rotate a List

Beginner · Lists

Rotating a list shifts every element along by some number of places, and the elements that fall off one end come back at the other. Rotating [1, 2, 3, 4, 5, 6] left by 2 gives [3, 4, 5, 6, 1, 2], and rotating it right by 2 gives [5, 6, 1, 2, 3, 4].

Program

rotate_a_list.py
numbers = [1, 2, 3, 4, 5, 6]
k = 2 # or: k = int(input("Rotate by how many places? "))
print("Original list:", numbers)
# Rotating by 6 places brings a 6-element list back to the start
k = k % len(numbers)
# Left rotation: the first k elements move to the end
left = numbers[k:] + numbers[:k]
print(f"Rotated left by {k}:", left)
# Right rotation: the last k elements move to the front
right = numbers[-k:] + numbers[:-k]
print(f"Rotated right by {k}:", right)
Output
Original list: [1, 2, 3, 4, 5, 6]
Rotated left by 2: [3, 4, 5, 6, 1, 2]
Rotated right by 2: [5, 6, 1, 2, 3, 4]

How it works

  1. k % len(numbers) keeps k smaller than the length, so rotating by 8 places works the same as rotating by 2.
  2. numbers[k:] is everything from index k to the end, and numbers[:k] is the first k elements; joining them in that order rotates left.
  3. numbers[-k:] is the last k elements, and numbers[:-k] is everything before them; putting the last ones first rotates right.
  4. Slicing makes new lists, so numbers itself is not changed.

Other ways to write it

One step at a time

One step at a time
numbers = [1, 2, 3, 4, 5, 6]
for step in range(1, 3):
first = numbers.pop(0) # take the first element off
numbers.append(first) # and put it on the end
print(f"After step {step}:", numbers)
Output
After step 1: [2, 3, 4, 5, 6, 1]
After step 2: [3, 4, 5, 6, 1, 2]

Each step moves one element from the front to the back, which shows what a left rotation does. It changes the list itself.

Using collections.deque

Using collections.deque
from collections import deque
items = deque([1, 2, 3, 4, 5, 6])
items.rotate(2) # a positive number rotates right
print("Rotated right by 2:", list(items))
items.rotate(-3) # a negative number rotates left
print("Then left by 3:", list(items))
Output
Rotated right by 2: [5, 6, 1, 2, 3, 4]
Then left by 3: [2, 3, 4, 5, 6, 1]

A deque (double-ended queue) has a built-in rotate() that is fast even for long lists.

Try it yourself

Set k = 8 and check that the result is the same as for k = 2.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises