Python Program to Swap the First and Last Value of a List



When it is required to swap the first and last values of a list using Python, a method can be defined, that uses a simple sorting technique to sort the values.

Below is a demonstration of the same −

Example

 Live Demo

def list_swapping(my_list):
   size_of_list = len(my_list)

   temp = my_list[0]
   my_list[0] = my_list[size_of_list - 1]
   my_list[size_of_list - 1] = temp

   return my_list

my_list = [34, 21, 56, 78, 93, 20, 11, 9]
print("The list is :")
print(my_list)
print("The function to swap the first and last elements is swapped")
print(list_swapping(my_list))

Output

The list is :
[34, 21, 56, 78, 93, 20, 11, 9]
The function to swap the first and last elements is swapped
[9, 21, 56, 78, 93, 20, 11, 34]

Explanation

  • A method named ‘list_swapping’ is defined.

  • It takes a list as a parameter.

  • The first and the last elements of the list are swapped.

  • The resultant list is returned as output.

  • Outside the function, a list is defined and displayed on the console.

  • The method is called bypassing this list as a parameter.

  • The output is displayed on the console.


Advertisements