Change Index of List in Python (2 Examples)
In this post, you’ll learn how to change indexes of elements in a list in Python.
The content of the tutorial looks as follows:
Let’s dig in!
Example Data
The following data will be used as a basis for this Python programming tutorial:
lst = ['a', 'b', 'c', 'd', 'e'] # create a sample list print(lst) # print lst # ['a', 'b', 'c', 'd', 'e']
As you can see, we created a list called lst
with five elements. Next, we will see the possible ways of changing the indexes of some elements.
Example 1: Rearrange Indexes by Slicing
In this example, I’ll explain how to use the pop function to remove an element at a certain index and how to insert it back into another index position using the insert method.
old_index = 1 # define old position new_index = 3 # define new position element = lst.pop(old_index) # remove and store item at old position lst.insert(new_index, element) # insert stored item into new position print(lst) # print lst # ['a', 'c', 'd', 'b', 'e']
As you can see, we removed the element at index 1, which corresponds to "b"
, then we stored it as element
. Afterward, we used the index method to put it back into the list lst
, but this time to index position 3, which is the old position of "d"
.
Let’s see what else we can do to change the indexes of elements!
Example 2: Rearrange Indexes by Swapping
Alternatively, you can swap the elements in different index positions using tuple unpacking. Assume we want to interchange the position of elements at index 1 and 3.
index1 = 1 # first index of interest index2 = 3 # second index of interest lst[index1], lst[index2] = lst[index2], lst[index1] # swap items in respective indexes print(lst) # print lst # ['a', 'd', 'c', 'b', 'e']
Now you can see how "b"
is replaced with "d"
and vice versa. Well done!
Video, Further Resources & Summary
Some time ago, I have released a video on the Statistics Globe YouTube channel, which explains the Python programming code of this tutorial. You can find the video below.
The YouTube video will be added soon.
Furthermore, you might read the related tutorials on this website. A selection of tutorials about related topics such as data elements, lists, and indices is listed below:
- Access Multiple List Elements by Index in Python
- Convert List to Dictionary with Index in Python
- Check if List Index Exists in Python
- Change Index of Element in List in Python
- Python Programming Tutorials
Summary: This post has demonstrated how to rearrange indexes of elements in a Python list in Python programming. If you have further questions, please let me know in the comments.
This page was created in collaboration with Cansu Kebabci. Have a look at Cansu’s author page to get more information about her professional background, a list of all his tutorials, as well as an overview on her other tasks on Statistics Globe.
Statistics Globe Newsletter