Explain Codes LogoExplain Codes Logo

How to switch position of two items in a Python list?

python
list-manipulation
swap
tuple-unpacking
Anton ShumikhinbyAnton Shumikhin·Feb 22, 2025
TLDR

Swap two elements in a Python list by simply inputting:

my_list[1], my_list[3] = my_list[3], my_list[1]

This effectively exchanges places of elements at index 1 and 3.

Swap items with unknown positions

When the positions of the items to be swapped are not known beforehand, list.index and parallel assignments can be applied:

idx1 = my_list.index('unknown1') # Finds Waldo idx2 = my_list.index('unknown2') # Finds Carmen Sandiego my_list[idx1], my_list[idx2] = my_list[idx2], my_list[idx1] # Swaps their hideouts

Above code will look for the indexes of 'unknown1' and 'unknown2' before swapping them. Swift and efficient, don't you think?

Swap using slicing

Let's mix things up a bit for adjacent items. Here, slicing works like a charm:

my_list[1:3] = my_list[1:3][::-1] # Pulls a Back to the Future trick

Just like that, we've reversed the slice with elements at index 1 and 2.

The tuple assignment charm

No indexes? No problem! Harness the magic of tuple unpacking:

idx1, idx2 = (my_list.index('obscure1'), my_list.index('obscure2')) # Pairs Sherlock and Watson my_list[idx1], my_list[idx2] = my_list[idx2], my_list[idx1] # Swaps their disguises

Voila! A graceful swap, infused with the elixir of tuple unpacking.

Classic swap with a sidekick

Introduce a temporary variable for a timeless twist to swapping:

sidekick = my_list[idx1] # Robin, hold this. my_list[idx1] = my_list[idx2] # Batman, here's your mask. my_list[idx2] = sidekick # Robin, give me back my mask.

A classic three-step dance that's intuitively attractive to Python initiates.

Optimized swap for a single showdown

If a list is expecting only one swap, optimize it to finish faster than a cowboy's duel:

items_to_swap = ('mystery1', 'mystery2') for item in my_list: if item in items_to_swap: idx1, idx2 = my_list.index(items_to_swap[0]), my_list.index(items_to_swap[1]) my_list[idx1], my_list[idx2] = my_list[idx2], my_list[idx1] break # Exits the gunfight after disabling the villain