Sling Academy
Home/Python/Python: How to Swap 2 Elements in a List (2 Approaches)

Python: How to Swap 2 Elements in a List (2 Approaches)

Last updated: June 16, 2023

When writing code in Python, there might be cases where you need to exchange the position of 2 elements in a list to achieve a desired outcome or fulfill a particular requirement. This pithy, code-centric article will show you a couple of different ways to do so.

Using a temporary variable

This approach involves using a temporary variable to store the value of one element, swapping the values of the two elements, and then assigning the stored value to the other element.

# Define a list
my_list = ["A", "B", "C", "D", "E", "F"]

# Swap the element at index 2 and the element at index 4
temp = my_list[2]
my_list[2] = my_list[4]
my_list[4] = temp

# Print the result
print(my_list)

Output:

['A', 'B', 'E', 'D', 'C', 'F']

If you have to deal with this task many times, it’s better to define a reusable function like this:

def swap_elements(lst, i, j):
    temp = lst[i]
    lst[i] = lst[j]
    lst[j] = temp

This technique is simple, intuitive, and easy to understand. It also works for any type of element, even if they are not hashable or mutable.

Using tuple unpacking

This Pythonic solution involves using tuple unpacking to directly swap the values of the two elements without needing a temporary variable. The general syntax is as follows:

lst[i], lst[j] = lst[j], lst[i]

Example:

my_list = ["sling", "arrow", "bow", "academy"]

# Swap the element at index 1 and the last element
my_list[1], my_list[-1] = my_list[-1], my_list[1]
print(my_list)

Output:

['sling', 'academy', 'bow', 'arrow']

Conclusion

You’ve learned more than one approach to swapping 2 elements in a list. Both of them are concise and elegant. Choose the one you prefer to go with. Happy coding & have a nice day!

Next Article: Python: How to Compare 2 Lists (3 Approaches)

Previous Article: Python: 2 Ways to Find Common Elements in 2 Lists

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots