Reverse Array
Reverse a Python list by swapping symmetric positions. Students trace a half-length loop and calculate the partner index without swapping every pair twice.
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67# Reverse array8print(f"Original: {arr}")9for i in range(len(arr) // 2):10 arr[i], arr[len(arr) - 1 - i] = arr[len(arr) - 1 - i], arr[i]1112print(f"Reversed: {arr}")
Output
Enter array size: 5 Element 1: 1 Element 2: 2 Element 3: 3 Element 4: 4 Element 5: 5 Original: [1, 2, 3, 4, 5] Reversed: [5, 4, 3, 2, 1]
In this one
- Pair symmetric indexes
- Limit swaps to half
- Leave an odd center
How it works
- 1
Visit the first half of arr's indexes.
- 2
Pair i with len(arr) - 1 - i.
- 3
Swap each pair once and print the reversed list.
Edge cases
What happens to an odd middle element?
What happens to an odd middle element?
It remains in place.
Why stop at half the length?
Why stop at half the length?
Every swap handles two symmetric positions.
What's going on
Index i is paired with len(arr) - 1 - i. The loop stops after half the length using integer floor division.
Each pair swaps in place. An odd-length list has a center element that stays where it is. Visiting the whole list would swap pairs back again, undoing the reversal. Empty and one-element lists naturally require no swaps.
What happens to an odd middle element? It remains in place.
Why stop at half the length? Every swap handles two symmetric positions.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Does this allocate a reversed list?
Pick an answer to check it.
Question 2
What happens to an odd middle element?
Pick an answer to check it.
Questions people ask
What happens to an odd middle element?
It remains in place.
Why stop at half the length?
Every swap handles two symmetric positions.
Does this allocate a reversed list?
No, it swaps in place.
๐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