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.
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67# Rotate left8if len(arr) > 0:9 first = arr[0]10 for i in range(len(arr) - 1):11 arr[i] = arr[i + 1]12 arr[-1] = first1314print(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
Save the first value when arr is nonempty.
- 2
Copy each next value into the preceding slot.
- 3
Put the saved value at the last position.
Walk through Rotate Left by 1
arr = [1, 2, 3]
- 1.Save first = 1.
- 2.Copy 2 into index 0, then 3 into index 1.
- 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.
๐Related Content
- ๐
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- ๐
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- ๐ป
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum