A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-program-to-swap-two-elements-in-a-list/ below:

Python Program to Swap Two Elements in a List

Python Program to Swap Two Elements in a List

Last Updated : 11 Jul, 2025

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:

Python
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.

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:

Related Article:


Python Program to Swap Two Elements in a List


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4