How to Rotate a List in Python
Rotate a list to the right by k positions using Python's list slicing and modulo arithmetic.
Python code
11 linesdef rotate_list_right(lst, k):
if not lst:
return lst
k = k % len(lst)
return lst[-k:] + lst[:-k] if k != 0 else lst
if __name__ == "__main__":
sample = [1, 2, 3, 4, 5, 6, 7]
for k in [0, 1, 3, 8, 20]:
print(f"k={k}: {rotate_list_right(sample, k)}")
Output
k=0: [1, 2, 3, 4, 5, 6, 7]
k=1: [7, 1, 2, 3, 4, 5, 6]
k=3: [5, 6, 7, 1, 2, 3, 4]
k=8: [7, 1, 2, 3, 4, 5, 6]
k=20: [1, 2, 3, 4, 5, 6, 7]
How it works
The key insight is using k % len(lst) to handle rotations larger than the list length, ensuring k is always within valid bounds. List slicing lst[-k:] takes the last k elements, while lst[:-k] takes the rest, and concatenating them produces the rotated list. The conditional checks if k is zero to return the original list, avoiding empty slice edge cases. This approach is O(n) in time and O(n) in space, making it efficient for most practical lists.
Common mistakes
- Forgetting to handle empty lists with a guard clause, causing a ZeroDivisionError
- Not using modulo when k exceeds list length, leading to incorrect rotations
- Mutating the original list in-place when a new list is expected
Variations
- Use `collections.deque` with `rotate(k)` for in-place rotation
- Implement an in-place algorithm with reversal: reverse whole list, then reverse first k and last n-k parts
Real-world use cases
- Scheduling tasks in a round-robin fashion by rotating a queue of worker IDs
- Paging through a carousel of featured products by rotating a list of item keys
- Implementing a circular buffer for rotating log files or sensor readings
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.