Header Ads

Python 3 Program to Swap First Value with Last Value Value in List

In This Post We Understand How to Swap First Value with Last Value in List

Code Program Example 1

#Python 3 Program to Swap first value with last value in List
#swap function

def  swapList(list1):
    size =
int(len(list1))
#swapping values
   
temp = list1[0]
    list1[
0] = list1[size - 1]
    list1[size-
1] = temp

#create List
list1 = [11,26,39,87,92, 47]
print("Before Swaping List Values")
print(list1)
#function Call
swapList(list1)
print("After Swapping List Values")
print(list1)

Output:

Code Program Example 2

In this Program we Create Dynamic List. User Enter the Length of List and then Enter the

Element of List. Swap the First Element of List with Last Element of List 

#Create Dynamci List
myList = []
n =
int(input("Enter the Number of Elements in List:"))
for i in range(0,n):
    value =
int(input("Enter  "+str(i+1)+" Element:"))
    myList.append(value)
print("Before Swapping List is")
print(myList)
#Swap the Element of List
temp = myList[0]
myList[
0] = myList[n-1]
myList[n-
1] = temp
print("After Swapping List is")
print(myList)

 Output:


No comments

Powered by Blogger.