Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Rotate Left by 1

Rotate a Python list one position left with manual shifts. Students save the first value, move remaining values safely, and wrap the saved value to the end.

IntermediatePhase 4 - Level 3: TransformationExample 7 of 10
rotate-left-by-1.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Rotate left
8if len(arr) > 0:
9 first = arr[0]
10 for i in range(len(arr) - 1):
11 arr[i] = arr[i + 1]
12 arr[-1] = first
13
14print(f"After left rotation: {arr}")

Output

Enter array size: 5
Element 1: 1
Element 2: 2
Element 3: 3
Element 4: 4
Element 5: 5
After left rotation: [2, 3, 4, 5, 1]

In this one

  • Save an overwritten endpoint
  • Shift left in order
  • Wrap rather than discard

How it works

  1. 1

    Save the first value when arr is nonempty.

  2. 2

    Copy each next value into the preceding slot.

  3. 3

    Put the saved value at the last position.

Walk through Rotate Left by 1

arr = [1, 2, 3]

  1. 1.Save first = 1.
  2. 2.Copy 2 into index 0, then 3 into index 1.
  3. 3.Write the saved 1 into the final slot: [2, 3, 1].

Edge cases

What if the list is empty?

What if the list is empty?

The guard skips all rotation work.

What if it has one value?

What if it has one value?

It remains unchanged.

What's going on

The first value is saved before any overwrite. The ascending index loop copies each next element into the preceding slot.

After shifting, arr[-1] receives the saved first value. Thus [1, 2, 3] becomes [2, 3, 1]. This preserves all elements unlike a shift that discards an endpoint. The nonempty guard protects both endpoint accesses.

What if the list is empty? The guard skips all rotation work.

What if it has one value? It remains unchanged.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why save the first value?

Pick an answer to check it.

Question 2

What if the list is empty?

Pick an answer to check it.

Questions people ask

What if the list is empty?

The guard skips all rotation work.

What if it has one value?

It remains unchanged.

Why save the first value?

The first shift would overwrite it.