Table of Contents
In this section, we will understand the python code to swap the first and last elements and display the new list.
list = [1, 2, 3, 4, 5] # sorting first and last values in variables f = list l = list[-1] # Placing the variable values at first and last index list[-1] = f list = l print("The new list is : ", list)
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.