Python3 List Swap Two Elements
# Python 3: How to Swap Two Elements in a List
Swapping the positions of two elements in a list is a common operation in Python, often used in sorting algorithms, data manipulation, and array-based problems.
In this tutorial, we will explore three different methods to swap two elements at specified positions in a Python list.
---
## Problem Description
Given a list and two positions (indices), we want to swap the elements at those positions.
For example, if we want to swap the 1st and 3rd elements (using 1-based indexing for user input, which corresponds to index `0` and index `2` in Python's 0-based indexing):
* **Input List:** `[23, 65, 19, 90]`
* **Positions to swap:** `pos1 = 1`, `pos2 = 3`
* **Output List:** `[19, 65, 23, 90]`
---
## Method 1: Using Pythonic Tuple Unpacking (Recommended)
The most elegant, efficient, and standard way to swap elements in Python is by using **tuple unpacking**. This approach does not require a temporary variable or any built-in list methods.
### Code Example
```python
def swap_positions(lst, pos1, pos2):
# Swap elements using tuple unpacking
lst, lst = lst, lst
return lst
# Driver code
my_list = [23, 65, 19, 90]
pos1, pos2 = 1, 3
# Convert 1-based user positions to 0-based Python indices
print(swap_positions(my_list, pos1 - 1, pos2 - 1))
```
### Output
```python
[19, 65, 23, 90]
```
---
## Method 2: Using `pop()` and `insert()`
Another approach is to remove the elements from their respective positions using the `pop()` method and then insert them back at the swapped positions using the `insert()` method.
*Note: This method is less efficient because `pop()` and `insert()` operations shift elements in memory, resulting in $O(n)$ time complexity.*
### Code Example
```python
def swap_positions(lst, pos1, pos2):
# Pop the element at pos1
first_ele = lst.pop(pos1)
# Pop the element at pos2 (adjusted because the list size decreased by 1)
second_ele = lst.pop(pos2 - 1)
# Insert the elements back in swapped order
lst.insert(pos1, second_ele)
lst.insert(pos2, first_ele)
return lst
# Driver code
my_list = [23, 65, 19, 90]
pos1, pos2 = 1, 3
# Convert 1-based user positions to 0-based Python indices
print(swap_positions(my_list, pos1 - 1, pos2 - 1))
```
### Output
```python
[19, 65, 23, 90]
```
---
## Method 3: Using a Temporary Tuple
This method is a variation of Method 1. It explicitly packs the elements into a temporary tuple variable `get` and then unpacks them back into the list in reverse order.
### Code Example
```python
def swap_positions(lst, pos1, pos2):
# Pack the elements into a temporary tuple
get = lst, lst
# Unpack them back into the swapped positions
lst, lst = get
return lst
# Driver code
my_list = [23, 65, 19, 90]
pos1, pos2 = 1, 3
# Convert 1-based user positions to 0-based Python indices
print(swap_positions(my_list, pos1 - 1, pos2 - 1))
```
### Output
```python
[19, 65, 23, 90]
```
---
## Key Considerations
1. **Index Out of Range:** Always ensure that the specified indices (`pos1` and `pos2`) are within the valid range of the list (`0` to `len(lst) - 1`). Attempting to swap elements outside this range will raise an `IndexError`.
2. **0-Based vs. 1-Based Indexing:** Python lists use 0-based indexing. If your application accepts 1-based index inputs from users, remember to subtract `1` from the positions before passing them to your swap function.
3. **In-Place Modification:** All the methods shown above modify the original list in-place. If you need to keep the original list unchanged, make a copy of the list first using `lst.copy()` or slicing `lst[:]`.
YouTip