Swap First & Last Elements
Swap a list's first and last elements safely. Students use a nonempty guard, negative indexing, and simultaneous assignment without overwriting either endpoint.
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67# Swap first and last8if len(arr) > 0:9 arr[0], arr[-1] = arr[-1], arr[0]1011print(f"After swap: {arr}")
Output
Enter array size: 5 Element 1: 1 Element 2: 2 Element 3: 3 Element 4: 4 Element 5: 5 After swap: [5, 2, 3, 4, 1]
In this one
- Guard endpoint access
- Use negative indexing
- Swap simultaneously
How it works
- 1
Check that arr is nonempty.
- 2
Read both old endpoints on the assignment's right side.
- 3
Write them into exchanged positions.
Edge cases
What if the list is empty?
What if the list is empty?
The guard skips the swap.
What if it has one value?
What if it has one value?
That value swaps with itself and stays unchanged.
What's going on
The guard checks that an endpoint exists before indexing. arr[0] is the first element and arr[-1] the last.
The right-hand pair is evaluated before either assignment, preserving both original values. Only endpoints move; middle entries keep their positions. For a one-element list, both references name the same slot, so the swap leaves it unchanged.
What if the list is empty? The guard skips the swap.
What if it has one value? That value swaps with itself and stays unchanged.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why use paired assignment?
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 the swap.
What if it has one value?
That value swaps with itself and stays unchanged.
Why use paired assignment?
Both old endpoint values are captured before writing.
๐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