Python Program to Swap First and Last Elements in list

Swap first and last element in list python; Through this tutorial, i am going to show you how to swap or interchange first and last element in list python.

Python Program to Swap Elements in List

Now, i write a programs to swap the first and last value of a list in python; as shown below:

  • Python Program to Swap the First and Last Element in List using for loop.
  • Python Program to Swap the First and Last Element in List using Function.

Python Program to Swap the First and Last Element in List using For loop

  • Declare a number list in program.
  • Get input number of elements in the list from user and store it in a variable.
  • Iterate for loop to take value one by one and insert them into the list using append() method.
  • Swap first and the last element in the list.
  • Print swapped first and last element..
# Python Program to Swap the First and Last Value of a List
     
NumList = []
#how many elements in list
Number = int(input("How many elements in list :- "))
    
for i in range(1, Number + 1):
    value = int(input("Please enter the Value of %d Element :- " %i))
    NumList.append(value)
#print list before swapping
print("\nList before swapping of elements :-\n",NumList)
# Swap list 
temp=NumList[0]
NumList[0]=NumList[Number-1]
NumList[Number-1]=temp
  
print("List after swapping of elements :-\n",NumList) 

After executing the program, the output will be:

How many elements in list :-  5
Please enter the Value of 1 Element :-  5
Please enter the Value of 2 Element :-  4
Please enter the Value of 3 Element :-  3
Please enter the Value of 4 Element :-  2
Please enter the Value of 5 Element :-  1

List before swapping of elements :-
 [5, 4, 3, 2, 1]
List after swapping of elements :-
 [1, 4, 3, 2, 5]

Python Program to Swap the First and Last Element in List using Function

  • Define a function to swap elements with the list sl as a parameter.
  • Swap elements sl[0] and sl[n-1] using a third variable.
  • Return the swapped list.
  • Define the list values.
  • Pass the list in the function and print the result.
#swap first and last element in list

# Swap function
def swapList(sl):
    n = len(sl)
      
    # Swapping 
    temp = sl[0]
    sl[0] = sl[n - 1]
    sl[n - 1] = temp
      
    return sl
      
l = [10, 14, 5, 9, 56, 12]

print(l)
print("Swapped list: ",swapList(l))

After executing the program, the output will be:

[10, 14, 5, 9, 56, 12]
Swapped list: [12, 14, 5, 9, 56, 10]

Recommended Python Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *