Header Ads

How do you switch two elements in a list in Python?

Question Source 

Swapping list elements can by done by declaring a temporary variable or by simple swap i.e. comma assignment

Here I will be Using Inbuilt list.pop() function to switch to element in a list in Python
Python list pop() is an inbuilt function in Python that removes and returns the last value from the List or the given index value.

Code :

def swapPos(l, p1, p2):
    # poping out values from the list
    f1 = l.pop(p1)
    f2 = l.pop(p2-1)

    # inserting values into list  
    l.insert(p1, f2)
    l.insert(p2, f1)
    return l
   
list = [24, 66, 20, 91]
pos1 = 2
pos2 = 4
print(swapPos(list, pos1-1, pos2-1))


Output :

[24, 91, 20, 66]

Explanation :

We have defined swapPos() function which takes 3 arguments i.e. l, p1, p2. This function will swap position 'p1' and 'p2' in list 'l'. pop method is used to pop the element from the list and insert method is used to insert the elements into the list.
The follow chart of the working is given below :

Flow Chart :




Post a Comment

0 Comments