Swap Elements at Even and Odd Locations

AIM

To write a Python program that inputs a list of numbers and swaps elements at even locations with elements at odd locations.

Note: In this program, even and odd locations refer to indices. Index 0 (even) swaps with index 1 (odd), index 2 (even) swaps with index 3 (odd), and so on.

ALGORITHM

  1. Start
  2. Initialize an empty list L
  3. Input the size of the list from user
  4. Use a loop to input elements and append them to the list
  5. Display the original list
  6. Use a loop with step 2 to iterate through even indices (0, 2, 4, ...)
  7. For each even index i, swap L[i] with L[i+1] using temporary variables
  8. Display the list after swapping
  9. Stop

PROGRAM

# Input a list of numbers and swap elements at even location with odd location

# Code to get list from user
L = []
N = int(input("Enter the size of the list: "))
print("Enter the elements one by one:")
for i in range(N):
    Element = int(input("-> "))
    L.append(Element)

print("The given List is:")
print(L)

# Swap the elements at even location with the elements at odd location
for i in range(0, N, 2):
    if i + 1 < N:  # Check if odd index exists
        temp1 = L[i]
        temp2 = L[i + 1]
        L[i] = temp2
        L[i + 1] = temp1

print("\nThe List after swapping is:")
print(L)

# Alternative method using tuple unpacking
print("\n" + "=" * 50)
print("ALTERNATIVE METHOD - Using Tuple Unpacking")
print("=" * 50)

# Reset the list for demonstration
L2 = []
N2 = int(input("\nEnter the size of the list: "))
print("Enter the elements one by one:")
for i in range(N2):
    Element = int(input("-> "))
    L2.append(Element)

print("The given List is:")
print(L2)

# Swap using tuple unpacking (Pythonic way)
for i in range(0, N2, 2):
    if i + 1 < N2:
        L2[i], L2[i + 1] = L2[i + 1], L2[i]

print("\nThe List after swapping is:")
print(L2)

# Method 3: Function-based approach
def swap_even_odd(lst):
    """Function to swap elements at even and odd positions"""
    n = len(lst)
    for i in range(0, n, 2):
        if i + 1 < n:
            lst[i], lst[i + 1] = lst[i + 1], lst[i]
    return lst

print("\n" + "=" * 50)
print("FUNCTION-BASED APPROACH")
print("=" * 50)

# Demo with predefined list
demo_list = [10, 20, 30, 40, 50, 60, 70]
print(f"\nOriginal list: {demo_list}")
swapped_list = swap_even_odd(demo_list.copy())
print(f"After swapping: {swapped_list}")

# Demo with odd number of elements
odd_list = [1, 2, 3, 4, 5]
print(f"\nOriginal odd list: {odd_list}")
swapped_odd = swap_even_odd(odd_list.copy())
print(f"After swapping: {swapped_odd}")

OUTPUT

Enter the size of the list: 6

Enter the elements one by one:

-> 10

-> 20

-> 30

-> 40

-> 50

-> 60

The given List is:

[10, 20, 30, 40, 50, 60]

The List after swapping is:

[20, 10, 40, 30, 60, 50]

==================================================

FUNCTION-BASED APPROACH

==================================================

Original list: [10, 20, 30, 40, 50, 60, 70]

After swapping: [20, 10, 40, 30, 60, 50, 70]

Original odd list: [1, 2, 3, 4, 5]

After swapping: [2, 1, 4, 3, 5]

CONCLUSION

Thus, the given program was successfully executed and the output was verified as per the expected result.

VIVA QUESTIONS

  1. What does range(0, N, 2) do in this program?

    range(0, N, 2) generates a sequence starting from 0, up to N-1, with a step of 2. This gives us even indices: 0, 2, 4, 6, etc.

  2. Why do we check if i+1 < N before swapping?

    This prevents IndexError when the list has odd number of elements. The last element at even index would not have a corresponding odd index to swap with.

  3. What happens if the list has only one element?

    If the list has only one element, the loop range(0, 1, 2) will execute once with i=0, but the condition i+1 < N (0+1 < 1) will be false, so no swapping occurs.

  4. What is the advantage of tuple unpacking over temporary variables?

    Tuple unpacking (a, b = b, a) is more concise, readable, and Pythonic. It eliminates the need for temporary variables and reduces the chance of errors.

  5. How would you modify this program to swap every 3rd element?

    Change the range to range(0, N, 3) and swap L[i] with L[i+2], ensuring i+2 < Nto avoid index errors.

  6. What is the time complexity of this swapping algorithm?

    The time complexity is O(n) where n is the number of elements, as we iterate through the list once with step 2, performing constant-time swap operations.

  7. Can this program work with strings or other data types?

    Yes, the swapping logic works with any data type. You would just need to modify the input section to accept strings or other types instead of integers.

  8. How would you swap elements at specific user-defined positions?

    Take two position inputs from user, validate they are within list bounds, then swap using L[pos1], L[pos2] = L[pos2], L[pos1].

Related Resources

List Tips

  • • Always check array bounds before accessing
  • • Use tuple unpacking for clean swaps
  • • Consider edge cases like empty or single-element lists
  • • Test with both even and odd length lists

Practice More

Try more list manipulation programs to strengthen your skills.

View All Programs →