Input a list of numbers and swap elements at even locations with elements at odd locations
Expt. No.20
Page No.40
Swap even and odd positions
Aim
To write a Python program that swaps each element at an even index with the element at the next (odd) index in a list.
Concepts used
Algorithm
- Input n and then n numbers into a list.
- For i = 0, 2, 4 … up to n−2, swap the elements at i and i+1.
- If n is odd, the last element has no partner and stays in place.
- Display the list before and after.
Program
# Swap elements at even locations with elements at odd locations n = int(input("How many elements? "))lst = []for i in range(n): lst.append(int(input("Enter element: ")))print("Original list :", lst) for i in range(0, n - 1, 2): lst[i], lst[i + 1] = lst[i + 1], lst[i]print("After swapping:", lst)
A marked line continues the line above it. In your file, write it on the same line.
Output
Run 1
$ python swap_even_odd_positions.py
How many elements? 6
Enter element: 10
Enter element: 20
Enter element: 30
Enter element: 40
Enter element: 50
Enter element: 60
Original list : [10, 20, 30, 40, 50, 60]
After swapping: [20, 10, 40, 30, 60, 50]
Run 2
$ python swap_even_odd_positions.py
How many elements? 5
Enter element: 1
Enter element: 2
Enter element: 3
Enter element: 4
Enter element: 5
Original list : [1, 2, 3, 4, 5]
After swapping: [2, 1, 4, 3, 5]
✓ Printed by running this program, not typed by hand.
Result
[10, 20, 30, 40, 50, 60] became [20, 10, 40, 30, 60, 50]. For the odd-length list [1, 2, 3, 4, 5] the last element stayed in place: [2, 1, 4, 3, 5].
Viva voce: what the examiner may ask
01Why does the loop stop at n − 1?
The last value of i must leave room for i + 1; stopping at n − 1 avoids an IndexError when n is odd.
02What does the third argument of range(0, n - 1, 2) do?
It is the step, so i takes only even values 0, 2, 4 …
03Why can a list element be changed but not a string character?
Lists are mutable; strings are immutable.
Variations for the lab test
- Swap the first half of the list with the second half.
- Reverse the list without using
reverse(). - Move all even numbers to the front of the list.
! Common mistake Using
range(0, n, 2): for an odd n, i reaches n − 1 and lst[i + 1] raises IndexError.