Python Tutorial (33) - Example: Swap two elements at specified positions in a list

Time: Column:Python views:260

Define a List and Swap Two Elements at Specified Positions

This Python code demonstrates how to define a list and swap two elements at specified positions. Several implementations are provided, each achieving the same result.

Example:

Swap the first and third elements in the list.

Before Swap:

List = [23, 65, 19, 90], pos1 = 1, pos2 = 3

After Swap:

[19, 65, 23, 90]

Example 1: Basic Swap Using Tuple Assignment

def swapPositions(list, pos1, pos2):
    
    # Swap the elements at pos1 and pos2 using tuple assignment
    list[pos1], list[pos2] = list[pos2], list[pos1]
    
    return list

# Define the list and positions
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3

# Call the function and print the result (adjusting for zero-indexing)
print(swapPositions(List, pos1-1, pos2-1))

Output:

[19, 65, 23, 90]

Example 2: Swap Using pop() and insert()

def swapPositions(list, pos1, pos2):
    
    # Remove the elements at pos1 and pos2 and store them
    first_ele = list.pop(pos1)
    second_ele = list.pop(pos2 - 1)  # Adjust for the earlier removal
    
    # Insert them back in swapped positions
    list.insert(pos1, second_ele)
    list.insert(pos2, first_ele)
    
    return list

# Define the list and positions
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3

# Call the function and print the result (adjusting for zero-indexing)
print(swapPositions(List, pos1-1, pos2-1))

Output:

[19, 65, 23, 90]

Example 3: Swap Using a Tuple to Store Values

def swapPositions(list, pos1, pos2):
    
    # Store the elements at pos1 and pos2 in a tuple
    get = list[pos1], list[pos2]
    
    # Swap the elements using tuple unpacking
    list[pos2], list[pos1] = get
    
    return list

# Define the list and positions
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3

# Call the function and print the result (adjusting for zero-indexing)
print(swapPositions(List, pos1-1, pos2-1))

Output:

[19, 65, 23, 90]

Explanation:

  1. Example 1 uses tuple assignment to swap the two elements directly.

  2. Example 2 demonstrates how to remove elements using pop() and reinsert them at the desired positions using insert().

  3. Example 3 shows how to use a tuple to store the elements temporarily before swapping them.

All implementations result in the specified elements being swapped effectively, producing the same output.