Swap Alternate Elements
Swap adjacent pairs in a Python list with a step-two loop. Students trace safe partner indexes and see why an unmatched final element stays in place.
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 alternate8for i in range(0, len(arr) - 1, 2):9 arr[i], arr[i + 1] = arr[i + 1], arr[i]1011print(f"After swap: {arr}")
Output
Enter array size: 6 Element 1: 1 Element 2: 2 Element 3: 3 Element 4: 4 Element 5: 5 Element 6: 6 After swap: [2, 1, 4, 3, 6, 5]
In this one
- Advance by pairs
- Avoid an invalid partner
- Retain an unmatched tail
How it works
- 1
Choose pair starts with step two.
- 2
Stop before the last possible unpaired index.
- 3
Swap arr[i] with arr[i + 1].
Edge cases
What happens to an odd final element?
What happens to an odd final element?
It has no partner and stays unchanged.
What if the list is empty?
What if the list is empty?
The range contains no pair starts.
What's going on
The loop chooses indexes zero, two, four, and so on. Each i swaps with i + 1.
Stopping before len(arr) - 1 ensures a partner exists. For [1, 2, 3, 4, 5], the result is [2, 1, 4, 3, 5]. This changes neighboring pairs, not every other value with the same distant partner.
What happens to an odd final element? It has no partner and stays unchanged.
What if the list is empty? The range contains no pair starts.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why use a step of two?
Pick an answer to check it.
Question 2
What happens to an odd final element?
Pick an answer to check it.
Questions people ask
What happens to an odd final element?
It has no partner and stays unchanged.
What if the list is empty?
The range contains no pair starts.
Why use a step of two?
Each swap already handles two adjacent positions.
๐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