Program to swap first and last elements in the list in Python

Introduction

In this section, we will understand the python code to swap the first and last elements and display the new list.

Program to swap first and last elements in the list

Program

list = [1, 2, 3, 4, 5]
# sorting first and last values in variables
f = list[0]
l = list[-1]
# Placing the variable values at first and last index
list[-1] = f
list[0] = l
print("The new list is : ", list)

 

Output:

Program to swap first and last elements in the list Output

Explanation

In the above python code, we have created a list with few elements. To swap the values we have created two variables f and l to store the value of elements at first position (index 0) and last position (index -1). Now we assign the interchanged values to the respective indexes and display the result.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.