Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Swap Alternate Elements

Swap adjacent pairs in a Python list with a step-two loop. Students trace safe partner indexes and see why an unmatched final element stays in place.

IntermediatePhase 4 - Level 3: TransformationExample 9 of 10
swap-alternate-elements.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Swap alternate
8for i in range(0, len(arr) - 1, 2):
9 arr[i], arr[i + 1] = arr[i + 1], arr[i]
10
11print(f"After swap: {arr}")

Output

Enter array size: 6
Element 1: 1
Element 2: 2
Element 3: 3
Element 4: 4
Element 5: 5
Element 6: 6
After swap: [2, 1, 4, 3, 6, 5]

In this one

  • Advance by pairs
  • Avoid an invalid partner
  • Retain an unmatched tail

How it works

  1. 1

    Choose pair starts with step two.

  2. 2

    Stop before the last possible unpaired index.

  3. 3

    Swap arr[i] with arr[i + 1].

Edge cases

What happens to an odd final element?

What happens to an odd final element?

It has no partner and stays unchanged.

What if the list is empty?

What if the list is empty?

The range contains no pair starts.

What's going on

The loop chooses indexes zero, two, four, and so on. Each i swaps with i + 1.

Stopping before len(arr) - 1 ensures a partner exists. For [1, 2, 3, 4, 5], the result is [2, 1, 4, 3, 5]. This changes neighboring pairs, not every other value with the same distant partner.

What happens to an odd final element? It has no partner and stays unchanged.

What if the list is empty? The range contains no pair starts.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why use a step of two?

Pick an answer to check it.

Question 2

What happens to an odd final element?

Pick an answer to check it.

Questions people ask

What happens to an odd final element?

It has no partner and stays unchanged.

What if the list is empty?

The range contains no pair starts.

Why use a step of two?

Each swap already handles two adjacent positions.