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.
Python code
12 linesdef 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
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
- Use a deque from collections to rotate in-place: `collections.deque(lst).rotate(-k)`.
- 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
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.