Python Program to Swap First and Last Element of a Given List
Python Program to Swap First and Last Element of a Given List
Hey Python Geeks,
In this python tutorial, I have shown how to swap first and last element of a list.
Consider a python list : list = [1,2,3,4,5,6,7,8,9]
Create a python function called Swap that takes above python list as input, you can name it whatever you want and that can be written as : def Swap(list):
Now, we have to swap first element to last element and that can be done as : list[0],list[-1]=list[-1],
list[0] is the first element of the list
list[-1] is the last element of the list
We swapped them successfully, now call the function to see the swapped list and that can be done as : Swap(list)
The code can be written as :
list = [1,2,3,4,5,6,7,8,9]
print("List before swapping",list)
def swap(list):
list[0],list[-1]=list[-1],
print("List after swapping",swap(list))
Comments
Post a Comment