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
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
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.
For a practical file: draw its flowchart or write its algorithm in steps.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises