Welcome folks today in this example we will be swapping
or interchanging
first and last elements inside a list in python. All the full source code of the application is given below.
Get Started
In order to get started you need to create an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# Python3 program to swap first # and last element of a list # Swap function def swapList(newList): size = len(newList) # Swapping temp = newList[0] newList[0] = newList[size - 1] newList[size - 1] = temp return newList # Driver code newList = [12, 35, 9, 56, 24] print("The original list is \n") print(newList) print("\n") print("The swapped list is ") print(swapList(newList)) |
Now if you execute the above python script by typing the below command as shown below
python app.py
Now you can see that we have successfully swapped
the first and last element inside the list