Python Program to Interchange First and Last Elements in a List

Python Program to Interchange First and Last Elements in a List | Swapping refers to the exchange of two elements, this is usually done with a list. In this section, we see methods to python swap list elements. The list is a container that stores elements of similar data types.

Python Program to Interchange First and Last Elements in a List

Here, we will see a code to swap the first and last element in list Python. We swap elements in list python by taking input from the user using a For Loop.

In the code, we have initialized new to an empty list, and also we are taking input from the user and storing it in n, then in the for loop, we take inputs for list elements and append it to empty list new.

Program description:- Write a program to swap the first and last element in the list Python

# Python program to interchange first and last elements in a list

# take inputs
new = []
n = int(input("Enter number of elements in the list: " ))
for i in range(0, n):
   ele = int(input("Enter list element " + str(i+1) + ": " ))
   new.append(ele)
print("List:", new)

# swap elements
temp = new[0]
new[0] = new[n-1]
new[n-1] = temp

# print new list
print("Swapped List:", new)

Output for the input values test-case-1:-

Enter number of elements in the list: 3
Enter list element 1: 5
Enter list element 2: 7
Enter list element 3: 9
List: [5, 7, 9]
Swapped List: [9, 7, 5]

Output for the input values test-case-2:-

Enter number of elements in the list: 5
Enter list element 1: 6
Enter list element 2: 7
Enter list element 3: 8
Enter list element 4: 9
Enter list element 5: 10
List: [6, 7, 8, 9, 10]
Swapped List: [10, 7, 8, 9, 6]

Output for the input values test-case-3:-

Enter number of elements in the list: 7
Enter list element 1: 1
Enter list element 2: 2
Enter list element 3: 3
Enter list element 4: 4
Enter list element 5: 5
Enter list element 6: 6
Enter list element 7: 7
List: [1, 2, 3, 4, 5, 6, 7]
Swapped List: [7, 2, 3, 4, 5, 6, 1]

Output for the input values test-case-4:-

Enter number of elements in the list: 10
Enter list element 1: 11
Enter list element 2: 12
Enter list element 3: 13
Enter list element 4: 14
Enter list element 5: 15
Enter list element 6: 16
Enter list element 7: 17
Enter list element 8: 18
Enter list element 9: 19
Enter list element 10: 20
List: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Swapped List: [20, 12, 13, 14, 15, 16, 17, 18, 19, 11]

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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