Python program to interchange first and last elements in a list (original) (raw)

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.

Python `

lst = [1, 2, 3, 4, 5] lst[0], lst[-1] = lst[-1], lst[0]

print( lst)

`

**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.

Python `

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:

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.

Python `

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.

Python `

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.

Python `

lst = [12, 35, 9, 56, 24] tmp = lst[0] lst[0] = lst[-1] lst[-1] = tmp print(lst)

`