Python Program to Swap the First and Last Element in a List

This is a Python Program to swap the first and last value of a list.

Problem Description

The program takes a list and swaps the first and last value of the list.

Problem Solution

1. Take the number of elements in the list and store it in a variable.
2. Accept the values into the list using a for loop and insert them into the list.
3. Using a temporary variable, switch the first and last element in the list.
4. Print the newly formed list.
5. Exit.

Program/Source Code

Here is source code of the Python Program to swap the first and last value of a list. The program output is also shown below.

a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
    element=int(input("Enter element" + str(x+1) + ":"))
    a.append(element)
temp=a[0]
a[0]=a[n-1]
a[n-1]=temp
print("New list is:")
print(a)
Program Explanation

1. User must enter the number of elements in the list and store it in a variable.
2. User must enter the values of elements into the list.
3. The append function obtains each element from the user and adds the same to the end of the list as many times as the number of elements taken.
4. A temporary variable is used to swap the first and last element in the list.
5. The newly formed list is printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter the number of elements in list:4
Enter element1:23
Enter element2:45
Enter element3:67
Enter element4:89
New list is:
[89, 45, 67, 23]
 
Case 2:
Enter the number of elements in list:3
Enter element1:56
Enter element2:34
Enter element3:78
New list is:
[78, 34, 56]

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.