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.- def swapElement(list, pos1, pos2):
- list[pos1], list[pos2] = list[pos2], list[pos1]
- return list
- ret = False
- while True:
- print("\n================= Swap Element in List =================\n\n")
- List = [53, 21, 54, 34, 34]
- pos1, pos2 = 2, 5
- print("Original List: ", List)
- print("\n")
- print("Swap List: ", swapElement(List, pos1-1, pos2-1))
- opt = input("\nDo you want to try again?(yes/no): ")
- if opt.lower() == 'yes':
- ret=False
- elif opt.lower() == 'no':
- ret=True
- print("Exiting program....")
- else:
- print("Please enter yes/no:")
- break
- if ret == False:
- 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
Add new comment
- 47 views