Swap First & Last Elements
Swap first and last elements of array.
IntermediatePhase 4 - Level 3: TransformationExample 5 of 10
swap-first-last-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 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]
What's going on
Use tuple unpacking to swap.
Key Concepts:
arr[0] is first element
arr[-1] is last element
Swap using tuple assignment
🔗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