Rotate Right by 1
Rotate a list one position right with manual shifts. Students preserve the last value and scan backward to avoid overwriting values that are still needed.
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 right8if len(arr) > 0:9 last = arr[-1]10 for i in range(len(arr) - 1, 0, -1):11 arr[i] = arr[i - 1]12 arr[0] = last1314print(f"After right rotation: {arr}")
Output
Enter array size: 5 Element 1: 1 Element 2: 2 Element 3: 3 Element 4: 4 Element 5: 5 After right rotation: [5, 1, 2, 3, 4]
In this one
- Copy backward safely
- Preserve an endpoint
- Rotate without losing values
How it works
- 1
Save the last value.
- 2
Shift preceding values right using descending indexes.
- 3
Write the saved value at index zero.
Edge cases
Why shift backward?
Why shift backward?
Forward shifts would overwrite later source values too early.
What happens for a one-element list?
What happens for a one-element list?
The shift loop is empty and the value is restored to itself.
What's going on
The last element is saved first. The loop then moves from the last index down to one, copying the previous element into each slot.
Moving backward preserves each source until it has been copied. Finally, arr[0] gets the saved last value. [1, 2, 3] becomes [3, 1, 2]. The guard makes empty lists safe; a single value rotates to itself.
Why shift backward? Forward shifts would overwrite later source values too early.
What happens for a one-element list? The shift loop is empty and the value is restored to itself.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which value wraps to the front?
Pick an answer to check it.
Question 2
Why shift backward?
Pick an answer to check it.
Questions people ask
Why shift backward?
Forward shifts would overwrite later source values too early.
What happens for a one-element list?
The shift loop is empty and the value is restored to itself.
Which value wraps to the front?
The original last value.
๐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