Python Program to Swap Two Elements in a List
Last Updated :
29 Nov, 2024
Improve
In this article, we will explore various methods to swap two elements in a list in Python. The simplest way to do is by using multiple assignment.
Example:
a = [10, 20, 30, 40, 50]
# Swapping elements at index 0 and 4
# using multiple assignment
a[0], a[4] = a[4], a[0]
print(a)
Output
[50, 20, 30, 40, 10]
Using a Temporary Variable
Another common method for swapping elements in a list is by using a temporary variable. This is a straightforward approach that works well in many programming languages not just in Python.
a = [10, 20, 30, 40, 50]
# Using a temporary variable
# to swap elements at index 2 and 4
temp = a[2]
a[2] = a[4]
a[4] = temp
print(a)
Output
[10, 20, 50, 40, 30]
Explanation:
- We store the value at index 2 (30) in a temporary variable temp.
- We then assign the value at index 4 (50) to index 2.
- Finally, we assign the value stored in temp (30) to index 4.
Related Article:
- Python Program to Swap Two Variables
- Python program to interchange first and last elements in a list
- Python Program to swap two numbers without using third variable
- Python Program to Swap elements in String list
- Swapping sublists over given range in Python