Rotating a List by k Positions in Python

Day 14/365: Rotating a List by k Positions in Python 🔁📦 Today I worked on a classic array/list problem: rotating a list to the right by k positions without using built‑in shortcuts. The goal: Given a list l = [1, 2, 3, 4, 5] and k = 2, the output should be: [4, 5, 1, 2, 3] Here’s the logic I used: I run a loop k times, because I want to rotate the list to the right by k positions. In each rotation: I first store the last element: last = l[-1] Then I shift every element one step to the right: Starting from the end and moving backwards: for j in range(len(l)-1, 0, -1): I set l[j] = l[j-1] so each position takes the value from its previous index. After this loop, the first position l[0] is empty (logically), so I place the old last element there: l[0] = last After repeating this process k times, the list is rotated right by k positions. 💡 What I learned: How to manually rotate a list step by step, instead of relying on slicing tricks. How backward loops work in Python using range(start, stop, step) with a negative step. Why thinking in terms of “shifting” elements helps in many array/list problems (rotations, circular buffers, games, etc.). How repeating a simple transformation k times can solve problems without complex math. Next, I’d like to explore: Handling large k values efficiently (e.g., using k % len(l)). Rotating to the left instead of the right. Solving the same problem using slicing and comparing both approaches. Day 14 done ✅ 351 more to go. Got any other list/array transformation problems (like cyclic shifts, sliding windows, or in‑place rearrangements)? Drop them in the comments—I’d love to try them next. #100DaysOfCode #365DaysOfCode #Python #Lists #LogicBuilding #DataStructures #CodingJourney #LearnInPublic #AspiringDeveloper

  • text

To view or add a comment, sign in

Explore content categories