Python Program to Swap Elements at Even and Odd Positions in a List
Beginner · Lists · CBSE class 11 practical list
This program swaps each element at an even position with the element right after it, at the next odd position: index 0 with 1, 2 with 3, and so on. If the list has an odd number of elements, the last one has no partner and stays where it is.
Program
swap_even_odd_positions.py
numbers = [10, 20, 30, 40, 50, 60, 70] # or: numbers = [int(x) for x in input("Enter numbers: ").split()]
print("Original list:", numbers)
# Visit the even positions 0, 2, 4, ... and swap each with the next one.
# Stopping before the last index leaves an unpaired last element alone.
for i in range(0, len(numbers) - 1, 2):
numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]
print("After swapping:", numbers)
Output
Original list: [10, 20, 30, 40, 50, 60, 70] After swapping: [20, 10, 40, 30, 60, 50, 70]
How it works
range(0, len(numbers) - 1, 2)gives the even positions 0, 2, 4 and so on, stepping by 2.- At each even position
i, the element is swapped with the one ati + 1. numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]swaps two values in one line, without a temporary variable.- Because the range stops before the last index, a list of odd length, like this one with 7 elements, keeps its last element in place.
Another way to write it
Building a new list
Building a new list
numbers = [1, 2, 3, 4, 5]
result = []
for i in range(0, len(numbers), 2):
if i + 1 < len(numbers): # is there a partner?
result.append(numbers[i + 1])
result.append(numbers[i])
print("Original list:", numbers)
print("Swapped list:", result)
Output
Original list: [1, 2, 3, 4, 5] Swapped list: [2, 1, 4, 3, 5]
This version leaves the original list unchanged, and checks i + 1 < len(numbers) before using the partner element.
Try it yourself
Remove the last element, 70, so the list has an even length, and run the program again.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises