Python program to swap two elements in a list
Given a list in Python and provided the positions of the elements, write a program to swap the two elements in the list.
Examples:
Input : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3 Output : [19, 65, 23, 90] Input : List = [1, 2, 3, 4, 5], pos1 = 2, pos2 = 5 Output : [1, 5, 3, 4, 2]
Approach #1: Simple swap
Since the positions of the elements are known, we can simply swap the positions of the elements.
Output:
[19, 65, 23, 90]
Approach #2 : Using Inbuilt list.pop()
function
Pop the element at pos1 and store it in a variable. Similarly, pop the element at pos2 and store it in another variable. Now insert the two popped element at each other’s original position.
Output:
[19, 65, 23, 90]
Approach #3 : Using tuple variable
Store the element at pos1 and pos2 as a pair in a tuple variable, say get. Unpack those elements with pos2 and pos1 positions in that list. Now, both the positions in that list are swapped.
Output:
[19, 65, 23, 90]
Approach #4 : Using comma assignment
Output:
[19, 65, 23, 90]
No comments:
Post a Comment
Your feedback is highly appreciated and will help us to improve our content.