How to Swap First and Last Element in a List using Python
In this tutorial, we will program 'How to Swap the First and Last Elements in a List using Python'. We will learn how to swap the first and last elements of a list, or vice versa. The objective is to enable you to swap element positions within a 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 can do it yourself with ease. The program I will show you covers the basics of programming for swapping element positions in a list. I will do my best to provide you with the easiest way to swap element positions. So, let's start with the 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 swapList(newList):
- newList[0], newList[-1] = newList[-1], newList[0]
- return newList
- ret = False
- while True:
- print("\n================== Swap First and Last Element in a List ==================\n\n")
- newList = [45, 23, 8, 34, 15]
- print("My List: ", newList)
- print("New List: ",swapList(newList))
- 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
The script defines a function swap_list that swaps the first and last elements of a given list. It then enters an infinite loop where it displays a predefined list, swaps its first and last elements using the swap_list function, and prints the modified list.
The user is prompted to decide whether to run the operation again or exit the program. If the user chooses to run again, the loop continues; otherwise, the program exits.
Output:
The How to Swap First and Last Element in a List using Python source code that I provide can be download below. Please kindly click the download button.
There you have it we successfully created How to Swap First and Last Element in a 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
- 115 views