How to Rotate an Array by k Steps in Python

This code rotates a list to the right by k positions using modulo arithmetic to handle k larger than the list length.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

13 lines
Python 3.9+
def rotate_array(nums, k):
    if not nums:
        return []
    n = len(nums)
    k = k % n
    return nums[-k:] + nums[:-k] if k else nums[:]

if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5, 6]
    k = 2
    result = rotate_array(arr, k)
    print(f"Original: {arr}")
    print(f"Rotated by {k}: {result}")

Output

stdout
Original: [1, 2, 3, 4, 5, 6]
Rotated by 2: [5, 6, 1, 2, 3, 4]

How it works

The function first checks for an empty list and returns an empty list as a safety guard. It then normalizes k using the modulo operator k % n, because rotating by more than the list length wraps around. The return statement uses slicing: nums[-k:] extracts the last k elements, and nums[:-k] gets the rest, then concatenates them to form the rotated list. If k becomes zero (meaning the rotation is a full cycle back to the original), it returns a copy of the original list to avoid mutating the caller's data.

Common mistakes

  • Forgetting to handle k larger than the list length without modulo
  • Overlooking the empty list case causing an index error
  • Mutating the original list unexpectedly rather than returning a new one

Variations

  1. Use `collections.deque` with `rotate(k)` for in-place rotation
  2. Implement a three-step reverse in-place rotation for O(1) extra space

Real-world use cases

  • Rotating log files or time-series data for efficient sliding-window analysis.
  • Cycling through queue items in a round-robin load balancer process.
  • Implementing a rotating buffer in embedded systems for sensor data processing.

Sponsored

Run this sample

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

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.