Given a Python list, the task is to swap the first and last elements of the list without changing the order of the remaining elements.
Example:
Input: [10, 20, 30, 40, 50]
Output: [50, 20, 30, 40, 10]
Below are several different methods to perform this task:
Using Direct Assignment
This method swaps the first and last elements by directly exchanging their positions in a single step.
lst = [1, 2, 3, 4, 5]
lst[0], lst[-1] = lst[-1], lst[0]
print( lst)
Output
[5, 2, 3, 4, 1]
Explanation: lst[0] and lst[-1] returns the first and the last element of the list, we can simply swap them using assignment operator.
Using Tuple Variable
This method temporarily groups the last and first elements into a tuple before swapping.
lst = [12, 35, 9, 56, 24]
pair = lst[-1], lst[0]
lst[0], lst[-1] = pair
print(lst)
Output
[24, 35, 9, 56, 12]
Explanation:
- pair = lst[-1], lst[0]: Packs the last and first elements into a tuple.
- lst[0], lst[-1] = pair: Unpacks the tuple back into the list in reversed order, swapping them.
Using the * Operator
This method splits the list into the first element, the middle part, and the last element, then places them back in swapped order.
lst = [12, 35, 9, 56, 24]
a, *mid, b = lst
lst = [b, *mid, a]
print(lst)
Output
[24, 35, 9, 56, 12]
Explanation: a gets the first element, b the last, mid the middle portion, and the list is rebuilt as [b, *mid, a].
Using Slicing
This method creates a new list by rearranging slices so the last element moves to the front and the first moves to the end.
lst = [12, 35, 9, 56, 24]
lst = lst[-1:] + lst[1:-1] + lst[:1]
print(lst)
Output
[24, 35, 9, 56, 12]
Explanation: lst[-1:] gives the last element, lst[1:-1] the middle part, and lst[:1] the first element, combining them swaps the ends.
Using a Temporary Variable
This method performs a manual swap using a separate variable to hold the first element.
lst = [12, 35, 9, 56, 24]
tmp = lst[0]
lst[0] = lst[-1]
lst[-1] = tmp
print(lst)
Output
[24, 35, 9, 56, 12]
Explanation:
- tmp = lst[0]: stores the first element.
- lst[0] = lst[-1]: assigns the last element to the first position.
- lst[-1] = tmp: puts the saved first element at the last position.