Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to swap two elements in a list
In Python programming, lists are a versatile and commonly used data structure. At times, we may need to swap the positions of two elements within a list to reorganize data or perform specific operations.
This article explores different methods to swap two elements in a list, from basic temporary variable approach to Python's elegant tuple unpacking technique.
Understanding the Problem
Swapping two elements in a list means exchanging their positions. Given a list and two indices (i and j), we want to interchange the elements at those positions.
For example, if we have a list [1, 2, 3, 4, 5] and want to swap elements at indices 1 and 3, the result should be [1, 4, 3, 2, 5] where element 2 (at index 1) is swapped with element 4 (at index 3).
Method 1: Using Temporary Variable
The traditional approach uses a temporary variable to store one element during the swap ?
def swap_with_temp(numbers, i, j):
# Store first element in temporary variable
temp = numbers[i]
# Assign second element to first position
numbers[i] = numbers[j]
# Assign temporary value to second position
numbers[j] = temp
return numbers
# Example usage
numbers = [1, 2, 3, 4, 5]
print("Original List:", numbers)
result = swap_with_temp(numbers.copy(), 1, 3)
print("Swapped List:", result)
Original List: [1, 2, 3, 4, 5] Swapped List: [1, 4, 3, 2, 5]
Method 2: Using Tuple Unpacking (Pythonic Way)
Python's tuple unpacking provides an elegant one-liner solution ?
def swap_with_tuple(numbers, i, j):
# Swap using tuple unpacking
numbers[i], numbers[j] = numbers[j], numbers[i]
return numbers
# Example usage
numbers = [1, 2, 3, 4, 5]
print("Original List:", numbers)
result = swap_with_tuple(numbers.copy(), 1, 3)
print("Swapped List:", result)
Original List: [1, 2, 3, 4, 5] Swapped List: [1, 4, 3, 2, 5]
Method 3: Using List Methods
We can also use list methods like pop() and insert() for swapping ?
def swap_with_methods(numbers, i, j):
# Ensure i < j for correct indexing
if i > j:
i, j = j, i
# Remove elements (higher index first to avoid index shifting)
element_j = numbers.pop(j)
element_i = numbers.pop(i)
# Insert elements at swapped positions
numbers.insert(i, element_j)
numbers.insert(j, element_i)
return numbers
# Example usage
numbers = [1, 2, 3, 4, 5]
print("Original List:", numbers)
result = swap_with_methods(numbers.copy(), 1, 3)
print("Swapped List:", result)
Original List: [1, 2, 3, 4, 5] Swapped List: [1, 4, 3, 2, 5]
Comparison of Methods
| Method | Readability | Performance | Pythonic |
|---|---|---|---|
| Temporary Variable | Good | Fast | Traditional |
| Tuple Unpacking | Excellent | Fast | Very Pythonic |
| List Methods | Complex | Slower | Less efficient |
Complete Example with Error Handling
Here's a robust implementation with input validation ?
def safe_swap(numbers, i, j):
# Validate indices
if i < 0 or j < 0 or i >= len(numbers) or j >= len(numbers):
print("Error: Invalid indices")
return numbers
# Perform swap using tuple unpacking
numbers[i], numbers[j] = numbers[j], numbers[i]
return numbers
# Test with various cases
test_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
print("Original:", test_list)
# Valid swap
result1 = safe_swap(test_list.copy(), 0, 4)
print("Swap indices 0,4:", result1)
# Invalid indices
result2 = safe_swap(test_list.copy(), 2, 10)
print("Invalid swap (2,10):", result2)
Original: ['apple', 'banana', 'cherry', 'date', 'elderberry'] Swap indices 0,4: ['elderberry', 'banana', 'cherry', 'date', 'apple'] Error: Invalid indices Invalid swap (2,10): ['apple', 'banana', 'cherry', 'date', 'elderberry']
Conclusion
The tuple unpacking method (list[i], list[j] = list[j], list[i]) is the most Pythonic and readable approach for swapping list elements. Always validate indices to prevent runtime errors when working with user input.
