How to swap two or more elements in a list in python ?

Active May 19, 2021    /    Viewed 4262    /    Comments 0    /    Edit


Examples of how to swap two or more elements in a list in python :

Create a list

Let's first create a list in python:

l = ['a','e','c','d','b','f']

Swap two elements in a list

To swap for example the letters 'e' and 'b', a solution is to first get their indices:

idx1 = l.index('e')
idx2 = l.index('b')

returns here 1 and 4 here (Note: index() returns the first index in case of duplicates!).

And then use a tuple:

l[idx1], l[idx2] = l[idx2], l[idx1]

print(l)

returns

['a', 'b', 'c', 'd', 'e', 'f']

Another solution but less efficient is to do:

l = ['a','e','c','d','b','f']

tmp = l[1]
l[1] = l[4]
l[4] = tmp

print(l)

also returns

['a', 'b', 'c', 'd', 'e', 'f']

A thrid solution is to do

l = ['a','e','c','d','b','f']

idx1 = 1
idx2 = 4

e1 = l.pop(idx1)
e2 = l.pop(idx2-1) # -1 since we previously pop 'e'

print(e1,e2)

l.insert(idx1,e2)
l.insert(idx2,e1)

print(l)

also returns

['a', 'b', 'c', 'd', 'e', 'f']

Note that for the above example another solution in python is to do

l.sort()

returns

['a', 'b', 'c', 'd', 'e', 'f']

Swap multiple elements in a list

For example let's consider the following list:

l = ['c','e','a','d','b','f']

The goal is to swap ('b','d') and ('a','c')

Using what we learned previously, a solution is to do:

for i,j in [(1,4),(0,2)]:
        l[i], l[j] = l[j], l[i]

print(l)

gives

`['a', 'b', 'c', 'd', 'e', 'f']

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount