How to Rotate a List in Python

Rotate a list to the right by k positions using Python's list slicing and modulo arithmetic.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 15 views 0 copies

Python code

11 lines
Python 3.9+
def 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

stdout
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

  1. Use `collections.deque` with `rotate(k)` for in-place rotation
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.