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.
  1. def swapList(newList):
  2.  
  3. newList[0], newList[-1] = newList[-1], newList[0]
  4.  
  5. return newList
  6.  
  7.  
  8. ret = False
  9.  
  10.  
  11. while True:
  12. print("\n================== Swap First and Last Element in a List ==================\n\n")
  13.  
  14.  
  15. newList = [45, 23, 8, 34, 15]
  16.  
  17. print("My List: ", newList)
  18. print("New List: ",swapList(newList))
  19.  
  20. opt = input("\nDo you want to try again?(yes/no): ")
  21.  
  22. if opt.lower() == 'yes':
  23. ret=False
  24. elif opt.lower() == 'no':
  25. ret=True
  26. print("Exiting program....")
  27.  
  28. else:
  29. print("Please enter yes/no:")
  30. break
  31.  
  32. if ret == False:
  33. 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

Python Tutorials

Add new comment