VOOZH about

URL: https://www.geeksforgeeks.org/python/python-program-to-swap-two-elements-in-a-list/

⇱ Python Program to Swap Two Elements in a List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python Program to Swap Two Elements in a List

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


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.


Output
10 5

Explanation:

  • a = a ^ b: stores the XOR of a and b in a.
  • b = a ^ b: effectively assigns the original value of a to b.
  • a = a ^ b: assigns the original value of b to a.

Using a Temporary Variable


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:

Comment