To interchange the first and last element of a list in Python, we can use several approaches, and Python provides built-in functions that we can use for this purpose. however, we can use custom code as well to swap the first and last element of a list. The ways we will use:
Swapping two values by using the third variable
The pop() and insert() functions
List slicing technique
Iterable unpacking
So, let's get started.
This is the simplest way in which we use a third variable to hold an intermediate value while swapping the first and last element of a list. See the Python code.
# Python program to swap first and last element in a list
# Take a list
list1 = [45, 11, 15, 9, 56, 17]
print(list1)
# Take length
length = len(list1)
# Interchange first and last elements of a list
temp = list1[0]
list1[0] = list1[length - 1]
list1[length - 1] = temp
   Â
# Display result
print(list1)
Output:
[45, 11, 15, 9, 56, 17]
[17, 11, 15, 9, 56, 45]
In this program, we used the pop() function to remove an element and the insert() function to place an element at the specified index. See the Python code.
# Python program to swap first and last element in a list using pop and insert() function
# Take a list
list1 = [45, 11, 15, 9, 56, 17]
print(list1)
# Take length
length = len(list1)
# Interchange first and last elements of a list
first = list1.pop(0)Â Â Â
last = list1.pop(-1)Â
list1.insert(0, last)Â Â
list1.append(first)
# Display result  Â
print(list1)
Output:
[45, 11, 15, 9, 56, 17]
[17, 11, 15, 9, 56, 45]
In this program, we used the Slicing technique to swap the first and last element of a list. The last element is present at -1 index, and the first element is present at 0 index. So, we used these indexes to swap the elements.
# Python program to swap first and last element in a list by using slicing
# Take a list
list1 = [45, 11, 15, 9, 56, 17]
print(list1)
# Take length
length = len(list1)
# Interchange first and last elements of a list
list1[0], list1[-1] = list1[-1], list1[0]
# Display result
print(list1)
Output:
[45, 11, 15, 9, 56, 17]
[17, 11, 15, 9, 56, 45]
In this program, we used an iterable unpacking concept in which we can get the first and last elements easily. The syntax is a little strange but very useful. We should use this as it is a built-in feature of Python. See the Python code.
# Python program to swap first and last element in a list by using iterable unpacking
# Take a list
list1 = [45, 11, 15, 9, 56, 17]
print(list1)
# Take length
length = len(list1)
# Interchange first and last elements of a list
first, *middle, last = list1
list1 = [last, *middle, first]
# Display result
print(list1)
Output:
[45, 11, 15, 9, 56, 17]
[17, 11, 15, 9, 56, 45]
Useful References: