In programming, you’ll often find yourself dealing with lists of data. Python, like many other languages, offers a built-in data type for lists. Lists are used to store multiple items in a single variable.
Python provides various operations that can be performed on these lists, one of which is the swapping of items. Swapping items in a list can be crucial in sorting algorithms, in cases where you have to rearrange items in a list or simply swapping values for any other reason. In this tutorial, we’ll learn how to swap items in a list in Python.
Step 1: Create a List
First, we need a list to work with. Here’s a simple list with five elements:
1 |
items = [1, 3, 5, 7, 9] |
The data held within the list is output as follows:
[1, 3, 5, 7, 9]
Step 2: Swap Items Using a Temporary Variable
Arguably the most basic method to swap items in a list is by using a temporary variable. Here we’ll swap the second (index 1) and fourth (index 3) elements:
1 2 3 |
tmp = items[1] items[1] = items[3] items[3] = tmp |
This results in the following output:
[1, 7, 5, 3, 9]
Step 3: Swap Items directly
Python also allows you to swap items directly using a single line of code, which can be a more efficient method:
1 |
items[1], items[3] = items[3], items[1] |
The output after this operation is as follows:
[1, 3, 5, 7, 9]
Complete Code
If we combine all the steps into a cohesive piece of code, it will look like this:
1 2 3 4 5 6 7 |
items = [1, 3, 5, 7, 9] tmp = items[1] items[1] = items[3] items[3] = tmp print(items) # outputs: [1, 7, 5, 3, 9] items[1], items[3] = items[3], items[1] print(items) # outputs: [1, 3, 5, 7, 9] |
Conclusion
In this tutorial, we have gone through the basics of swapping items in a Python list. First, we understood how to do the swapping using a temporary variable, then we learned a more Pythonic way to do it directly in one line.
In conclusion, Python provides easy and flexible ways to manipulate your data so you can always choose the one that suits your needs the best.