How to Swap Element in List using Python

In this tutorial, we will program 'How to Swap Elements in a List using Python.' We will learn how to swap elements within a list. The objective is to quickly swap two elements in the list. I will provide a sample program to demonstrate the actual coding process in this tutorial.

This topic is very easy to understand. Just follow the instructions I provide, and you will be able to do it yourself with ease. The program I will show you covers the basics of programming for swapping elements in a list. I will do my best to provide you with a simple method for changing the index positions of elements in a list. So, let's start coding.

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. def swapElement(list, pos1, pos2):
  2.        
  3.         list[pos1], list[pos2] = list[pos2], list[pos1]
  4.         return list
  5.  
  6.  
  7. ret = False
  8.  
  9.  
  10. while True:
  11.         print("\n================= Swap Element in List =================\n\n")
  12.  
  13.  
  14.         List = [53, 21, 54, 34, 34]
  15.         pos1, pos2 = 2, 5
  16.  
  17.         print("Original List: ", List)
  18.         print("\n")
  19.         print("Swap List: ", swapElement(List, pos1-1, pos2-1))
  20.  
  21.         opt = input("\nDo you want to try again?(yes/no): ")
  22.  
  23.         if opt.lower() == 'yes':
  24.                 ret=False
  25.         elif opt.lower() == 'no':
  26.                 ret=True
  27.                 print("Exiting program....")
  28.  
  29.         else:
  30.                 print("Please enter yes/no:")
  31.                 break
  32.  
  33.         if ret == False:
  34.                 continue

This Python script swaps two elements in a list. The swapElement function takes a list and two positions, swaps the elements at those positions, and returns the modified list. The script repeatedly swaps the elements at positions 2 and 5 in the predefined list [53, 21, 54, 34, 34], displays the original and swapped lists, and then asks the user if they want to try again. The loop continues until the user decides to stop.

Output:


There you have it we successfully created How to Swap Element in List using Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Add new comment