Swap Alternate Elements
Swap alternate elements in array.
IntermediatePhase 4 - Level 3: TransformationExample 9 of 10
swap-alternate-elements.py
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]
What's going on
Swap pairs of adjacent elements.
Key Concepts:
Loop with step 2
Swap arr[i] with arr[i+1]
Process pairs
🔗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