Rotate List Left by k Positions in Python

Rotates a list left by k positions using slicing and modulo arithmetic to handle large k safely.

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

Python code

12 lines
Python 3.9+
def rotate_left(lst, k):
    if not lst:
        return []
    k = k % len(lst)
    return lst[k:] + lst[:k]

if __name__ == "__main__":
    my_list = [1, 2, 3, 4, 5]
    k = 2
    result = rotate_left(my_list, k)
    print(f"Original: {my_list}")
    print(f"After rotating left by {k}: {result}")

Output

stdout
Original: [1, 2, 3, 4, 5]
After rotating left by 2: [3, 4, 5, 1, 2]

How it works

The function uses slicing to split the list into two parts: elements from index k onward and elements before index k. Concatenating these parts shifts the first k elements to the end, rotating the list left. The modulo operation k % len(lst) ensures that rotating by a multiple of the list length returns the original list, and it also handles k larger than the list size. This approach runs in O(n) time and creates a new list, leaving the original unchanged.

Common mistakes

  • Forgetting to handle empty lists, causing a ZeroDivisionError in the modulo operation.
  • Not using modulo, so rotating by k > len(lst) produces wrong results or unnecessary full rotations.
  • Assuming the function mutates the original list when it actually returns a new list.

Variations

  1. Use a deque from collections to rotate in-place: `collections.deque(lst).rotate(-k)`.
  2. Implement with a loop that pops from the front and appends to the back k times (O(n*k) but simpler).

Real-world use cases

  • Rotating elements in a round-robin scheduler to change the order of tasks or servers.
  • Shifting a circular buffer's data structure when reading from a stream.
  • Rotating flashcards or questions in a quiz app so users see items in a different order each round.

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.