Python Program to Swap Two Elements in a List (original) (raw)

Last Updated : 30 Oct, 2025

In this article, we will explore various methods to swap two elements in a list in Python.

Using Multiple Assignment

Python `

a = [10, 20, 30, 40, 50] a[0], a[4] = a[4], a[0]

print(a)

`

Output

[50, 20, 30, 40, 10]

**Explanation: a[0], a[4] = a[4], a[0]: swaps the first (a[0]) and last (a[4]) elements of the list.

Using XOR Operator

We can swap two numbers without requiring a temporary variable by using the XOR operator (^). It works because applying XOR twice with the same value brings back the original number.

Python `

a = 5 b = 10

a = a ^ b b = a ^ b a = a ^ b

print(a, b)

`

**Explanation:

Using a Temporary Variable

Python `

a = [10, 20, 30, 40, 50]

temp = a[2] a[2] = a[4] a[4] = temp print(a)

`