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
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
k % len(numbers)keepsksmaller than the length, so rotating by 8 places works the same as rotating by 2.numbers[k:]is everything from indexkto the end, andnumbers[:k]is the firstkelements; joining them in that order rotates left.numbers[-k:]is the lastkelements, andnumbers[:-k]is everything before them; putting the last ones first rotates right.- Slicing makes new lists, so
numbersitself is not changed.
Other ways to write it
One step at a time
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
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.
Related programs
- Reverse a List
- Swap the First and Last Elements of a List
- Rotate a Matrix by 90 Degrees
- Implement a Circular Queue
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Find the Sum of Elements in a List
All Python programs · CBSE class 12 practical file · Python exercises