Python program to interchange first and last elements in a list
Given a list, write a Python program to swap first and last element of the list.
Examples:
Input : [12, 35, 9, 56, 24] Output : [24, 35, 9, 56, 12] Input : [1, 2, 3] Output : [3, 2, 1]
Approach #1: Find the length of the list and simply swap the first element with (n-1)th element.
Output:
[24, 35, 9, 56, 12]
Approach #2: The last element of the list can be referred as list[-1]
. Therefore, we can simply swap list[0]
with list[-1]
.
Output:
[24, 35, 9, 56, 12]
Approach #3: Swap the first and last element is using tuple variable. Store the first and last element as a pair in a tuple variable, say get, and unpack those elements with first and last element in that list. Now, the First and last values in that list are swapped.
Output:
[24, 35, 9, 56, 12]
Approach #4: Using * operand.
This operand proposes a change to iterable unpacking syntax, allowing to specify a “catch-all” name which will be assigned a list of all items not assigned to a “regular” name.
Output:
1 [2, 3] 4
Now let’s see the implementation of above approach:
Output:
[24, 35, 9, 56, 12]
Approach #5: Swap the first and last elements is to use inbuilt function list.pop()
. Pop the first element and store it in a variable. Similarily pop the last element and store it in another variable. Now insert the two popped element at each other’s original position.
Output:
[24, 35, 9, 56, 12]
No comments:
Post a Comment
Your feedback is highly appreciated and will help us to improve our content.