Input a list of numbers and swap elements at the even location with the elements at the odd location in Python, C and Java

“Input a list of numbers and swap the elements at the even locations with the elements at the odd locations” is a favourite practical question in school computer science. The idea is simple: the first element swaps with the second, the third with the fourth, and so on. The program teaches you three important things at once: list indexes, a loop that jumps by two, and the swap itself. In this guide you will learn how to write it in Python, C and Java, with the logic, dry runs, tested output and an interactive tool that shows every pair trading places.

★ Swap Even and Odd Position Elements

Type a list of numbers and watch every pair trade places.

Graphical view

Code

Output

What You Will Learn

Problem Statement

Input a list of numbers and swap the elements at the even locations with the elements at the odd locations.

For the list [10, 20, 30, 40, 50] the answer is [20, 10, 40, 30, 50]. The pairs (10, 20) and (30, 40) trade places. The last number, 50, has no partner, so it stays where it is. The interactive tool above accepts 1 to 10 numbers from -999 to 999.

Even and Odd Locations: Position Versus Index

People count positions from 1: the first element is at position 1 (odd), the second at position 2 (even), and so on. Python, C and Java count indexes from 0. So an odd position always has an even index, and an even position always has an odd index.

IndexPosition (counting from 1)Odd or even positionValue in [10, 20, 30, 40, 50]
01odd10
12even20
23odd30
34even40
45odd50

Swapping the element at an even location with the element at the odd location before it gives these pairs:

PositionsIndexes
1 and 20 and 1
3 and 42 and 3
5 and 64 and 5
2k − 1 and 2k2k − 2 and 2k − 1

The indexes of a pair are always i and i + 1, where i is 0, 2, 4, 6 and so on. That is why the loop in the programs starts at 0 and jumps by 2.

How to Swap Two Values

Imagine two glasses, one with milk and one with juice. You cannot pour one into the other directly, because they would mix. You need a third, empty glass. In a program the third glass is a temp variable:

  • temp = nums[i] saves the first value, so it is not lost.
  • nums[i] = nums[i + 1] copies the second value into the first place.
  • nums[i + 1] = temp puts the saved value into the second place.

If you skip the temp variable and write only the last two lines, both places end up holding the same number, and one value is lost for good.

Program 1: Swap in Place with a Temp Variable

Logic:

  • Read the numbers into nums and find their count n.
  • Loop i from 0 up to n − 2 in steps of 2. In Python this is range(0, n - 1, 2).
  • In each round, swap nums[i] and nums[i + 1] using temp.
  • Print the list.

The loop stops at n − 2 because the pair needs a partner at index i + 1. If n is odd, the last index n − 1 is never used as the first of a pair, so the last element stays in place automatically.

Python program

nums = list(map(int, input("Enter numbers separated by spaces: ").split()))
n = len(nums)
for i in range(0, n - 1, 2):
    temp = nums[i]
    nums[i] = nums[i + 1]
    nums[i + 1] = temp
print("After swapping:", nums)
C program
#include <stdio.h>
int main() {
    int n;
    printf("How many numbers? ");
    scanf("%d", &n);
    int nums[100];
    printf("Enter the numbers: ");
    for (int i = 0; i < n; i++) {
        scanf("%d", &nums[i]);
    }
    for (int i = 0; i < n - 1; i += 2) {
        int temp = nums[i];
        nums[i] = nums[i + 1];
        nums[i + 1] = temp;
    }
    printf("After swapping: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", nums[i]);
    }
    printf("\n");
    return 0;
}
Java program
import java.util.Scanner;
public class SwapProgram {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("How many numbers? ");
        int n = sc.nextInt();
        int[] nums = new int[n];
        System.out.print("Enter the numbers: ");
        for (int i = 0; i < n; i++) {
            nums[i] = sc.nextInt();
        }
        for (int i = 0; i < n - 1; i += 2) {
            int temp = nums[i];
            nums[i] = nums[i + 1];
            nums[i + 1] = temp;
        }
        System.out.print("After swapping: ");
        for (int i = 0; i < n; i++) {
            System.out.print(nums[i] + " ");
        }
        System.out.println();
    }
}

Sample output (odd number of elements):

Enter numbers separated by spaces: 10 20 30 40 50
After swapping: [20, 10, 40, 30, 50]

Another run (even number of elements):

Enter numbers separated by spaces: 5 8 2 9 7 1
After swapping: [8, 5, 9, 2, 1, 7]

Dry run for [10, 20, 30, 40, 50]:

iPositionstemp = nums[i]List beforeList after
01 and 210[10, 20, 30, 40, 50][20, 10, 30, 40, 50]
23 and 430[20, 10, 30, 40, 50][20, 10, 40, 30, 50]

The final list is [20, 10, 40, 30, 50]. The last element, 50, has no partner, so it stays where it is.

Dry run for [5, 8, 2, 9, 7, 1]:

iPositionstemp = nums[i]List beforeList after
01 and 25[5, 8, 2, 9, 7, 1][8, 5, 2, 9, 7, 1]
23 and 42[8, 5, 2, 9, 7, 1][8, 5, 9, 2, 7, 1]
45 and 67[8, 5, 9, 2, 7, 1][8, 5, 9, 2, 1, 7]

The final list is [8, 5, 9, 2, 1, 7].

The number of swaps is always n ÷ 2, rounded down:

Number of elements nSwaps madeOne element left over?
10yes
21no
52yes
63no
105no

Program 2: Build a New List

Sometimes the original list must stay unchanged. In that case, create an empty result list and fill it pair by pair. For each pair, add the second element first and then the first. If n is odd, copy the last element at the end.

Logic:

  • Start with an empty result list.
  • Loop i from 0 in steps of 2 while a partner exists: add nums[i + 1], then nums[i].
  • If n % 2 == 1, add the last element nums[n - 1] as it is.
  • Print result.

Python program

nums = list(map(int, input("Enter numbers separated by spaces: ").split()))
n = len(nums)
result = []
for i in range(0, n - 1, 2):
    result.append(nums[i + 1])
    result.append(nums[i])
if n % 2 == 1:
    result.append(nums[n - 1])
print("After swapping:", result)
C program
#include <stdio.h>
int main() {
    int n;
    printf("How many numbers? ");
    scanf("%d", &n);
    int nums[100];
    printf("Enter the numbers: ");
    for (int i = 0; i < n; i++) {
        scanf("%d", &nums[i]);
    }
    int result[100];
    for (int i = 0; i < n - 1; i += 2) {
        result[i] = nums[i + 1];
        result[i + 1] = nums[i];
    }
    if (n % 2 == 1) {
        result[n - 1] = nums[n - 1];
    }
    printf("After swapping: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", result[i]);
    }
    printf("\n");
    return 0;
}
Java program
import java.util.Scanner;
public class SwapProgram {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("How many numbers? ");
        int n = sc.nextInt();
        int[] nums = new int[n];
        System.out.print("Enter the numbers: ");
        for (int i = 0; i < n; i++) {
            nums[i] = sc.nextInt();
        }
        int[] result = new int[n];
        for (int i = 0; i < n - 1; i += 2) {
            result[i] = nums[i + 1];
            result[i + 1] = nums[i];
        }
        if (n % 2 == 1) {
            result[n - 1] = nums[n - 1];
        }
        System.out.print("After swapping: ");
        for (int i = 0; i < n; i++) {
            System.out.print(result[i] + " ");
        }
        System.out.println();
    }
}

Sample output:

Enter numbers separated by spaces: 1 2 3 4 5
After swapping: [2, 1, 4, 3, 5]

This version needs extra memory for the second list, but it keeps both the original and the swapped data, which is useful when you want to compare them or use the original later.

Other Ways to Write the Program

Method 3: Python’s tuple swap

Python can swap two values in a single line, without a temp variable. The right side is evaluated first, then both names are updated together.

nums = list(map(int, input("Enter numbers separated by spaces: ").split()))
n = len(nums)
for i in range(0, n - 1, 2):
    nums[i], nums[i + 1] = nums[i + 1], nums[i]
print("After swapping:", nums)

Sample output:

Enter numbers separated by spaces: 10 20 30 40 50
After swapping: [20, 10, 40, 30, 50]

C and Java have no tuple swap, so use the temp variable there.

Method 4: While loop

The same program with a while loop shows the counter clearly. The condition i + 1 < n means “there is still a partner for index i”, and i = i + 2 jumps to the next pair.

nums = list(map(int, input("Enter numbers separated by spaces: ").split()))
n = len(nums)
i = 0
while i + 1 < n:
    temp = nums[i]
    nums[i] = nums[i + 1]
    nums[i + 1] = temp
    i = i + 2
print("After swapping:", nums)

Sample output:

Enter numbers separated by spaces: 1 2 3 4
After swapping: [2, 1, 4, 3]

Method 5: Swapping without a temp variable using arithmetic

Numbers can be swapped with addition and subtraction. First store the sum in the first place. Then subtract the second from the sum to get the old first value, and subtract again to get the old second value. It works for numbers only, and for very large values in C or Java the sum can overflow an int, so temp is safer.

nums = list(map(int, input("Enter numbers separated by spaces: ").split()))
n = len(nums)
for i in range(0, n - 1, 2):
    nums[i] = nums[i] + nums[i + 1]
    nums[i + 1] = nums[i] - nums[i + 1]
    nums[i] = nums[i] - nums[i + 1]
print("After swapping:", nums)

Sample output:

Enter numbers separated by spaces: -3 4 -5 6
After swapping: [4, -3, 6, -5]

Method 6: Using a function

A function that returns a swapped copy leaves the original list alone and can be reused for any list.

def swap_pairs(items):
    result = list(items)
    for i in range(0, len(result) - 1, 2):
        result[i], result[i + 1] = result[i + 1], result[i]
    return result
nums = list(map(int, input("Enter numbers separated by spaces: ").split()))
print("Before swapping:", nums)
print("After swapping:", swap_pairs(nums))

Sample output:

Enter numbers separated by spaces: 5 8 2 9 7 1
Before swapping: [5, 8, 2, 9, 7, 1]
After swapping: [8, 5, 9, 2, 1, 7]

Method 7: Slicing

Python slices can swap all the pairs at once. nums[0:n - 1:2] picks the first element of every pair (indexes 0, 2, 4 …), and nums[1:n:2] picks the second element of every pair (indexes 1, 3, 5 …). The two slices always have the same length, so they can be swapped in one assignment, and an odd leftover element stays untouched. Be careful with the shorter form nums[0::2] and nums[1::2]: for an odd n it gives slices of different lengths, and Python raises a ValueError.

nums = list(map(int, input("Enter numbers separated by spaces: ").split()))
n = len(nums)
nums[0:n - 1:2], nums[1:n:2] = nums[1:n:2], nums[0:n - 1:2]
print("After swapping:", nums)

Sample output:

Enter numbers separated by spaces: 5 8 2 9 7 1
After swapping: [8, 5, 9, 2, 1, 7]

Variation: a tuple

A tuple cannot be changed, so swapping inside it gives a TypeError. Convert it to a list, swap, and convert back to a new tuple.

t = (10, 20, 30, 40)
lst = list(t)
for i in range(0, len(lst) - 1, 2):
    lst[i], lst[i + 1] = lst[i + 1], lst[i]
t = tuple(lst)
print("After swapping:", t)

Output:

After swapping: (20, 10, 40, 30)

Common Mistakes

  1. Looping up to n instead of n − 1. With range(0, n, 2) and an odd n, the last round reads nums[i + 1] beyond the end of the list and gives an IndexError. In C and Java the same mistake reads garbage or throws an exception.
  2. Jumping by 1 instead of 2. With a step of 1 the loop swaps neighbours again and again, and the numbers slide along the list. For [1, 2, 3, 4] the result is [2, 3, 4, 1] and not [2, 1, 4, 3].
  3. Forgetting the temp variable. Writing nums[i] = nums[i + 1] and then nums[i + 1] = nums[i] copies the same value twice, and the first value is lost.
  4. Mixing up position and index. The first element has index 0 but position 1. Start the loop at index 0, not 1. Starting at 1 would swap positions 2 and 3, which is a different program.
  5. Swapping the odd leftover with something. When n is odd, the last element has no partner. It must stay where it is. Do not try to swap it with index n.
  6. Reading the numbers as text. Without int, the numbers stay as strings. Swapping still works, but the output shows quotes around each item, and arithmetic does not.
  7. Trying to swap inside a tuple. A tuple is immutable, so convert it to a list first.

Practice Questions

  1. Swap the first and the last element of a list.
  2. Reverse a list without using reverse() or slicing.
  3. Swap every element with its neighbour on the right, moving the first element to the end of the list (a rotation by one).
  4. Swap the largest and the smallest number in a list.
  5. Print the elements at even positions and the elements at odd positions separately.
  6. Swap adjacent characters of a string, so “python” becomes “yphtno”.

Frequently Asked Questions

How do you swap even and odd position elements in a list in Python?

Loop with for i in range(0, n - 1, 2) and swap nums[i] with nums[i + 1], either with a temp variable or with the tuple swap nums[i], nums[i + 1] = nums[i + 1], nums[i].

Why does the loop jump by 2?

Each swap handles two elements, so the next pair starts two places further on. Jumping by 1 would swap the same elements again.

Why does the loop stop at n − 1?

Every swap needs an element at index i + 1. For the last index there is none, so the loop must stop one index before the end.

What happens to the last element when the list has an odd length?

It has no partner, so it stays where it is. For [10, 20, 30, 40, 50] the result is [20, 10, 40, 30, 50].

What is the difference between position and index?

Position counts from 1, and index counts from 0. The element at position 1 is at index 0, so odd positions have even indexes.

Why do we need a temp variable?

To hold one value while the two places trade. Without it, the first assignment overwrites a value that you still need.

Can I swap without a temp variable?

Yes. Python offers the tuple swap, and for numbers you can use addition and subtraction. In C and Java the temp variable is the clearest and safest way.

Does the program change the original list?

Program 1 changes it in place. Program 2 builds a new list and keeps the original unchanged.

Can the same program work on a tuple?

Not directly, because a tuple cannot be changed. Convert it to a list, swap, and convert back to a tuple.

What is the time complexity of this program?

It is O(n), because every element is touched once. The in-place version uses O(1) extra space, and the new-list version uses O(n).

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top