How to switch position of two items in a Python list?
Swap two elements in a Python list by simply inputting:
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:
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:
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:
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:
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:
Was this article helpful?