How to Add Values to the Middle of a List in Python
Learn to use the insert() method
Manipulating lists is a critical skill for any budding Pythonista. 9 out of 10 times, adding data to a list is done using the append() method, which adds the value to the end of a list. However, sometimes we need to add a value in the middle of a list.
In this quick and simple tutorial, we’ll introduce the insert() method—another native list method that can be used to add a value in the middle of a list.
How to Use the insert() Method
To use insert(), call the method from an already existing list. The method accepts two arguments, both of which are required. The first argument is the integer position within the list where the value will be added. The second argument is the value itself.
Let’s take a look at how we can add a value in the middle of an existing list using insert().tasks = [
'groceries',
'post office',
'movie'
]tasks.insert(2, 'shovel snow')print(tasks) # ['groceries', 'post office', 'shovel snow', 'movie']
Other Uses and Considerations
We could end the tutorial here, but let’s expound a bit on the insert() method.
Since we specify the index for the new value, we can use insert() to add a value at the start of a list as well.tasks = [
'groceries',
'post office',
'movie'
]tasks.insert(0, 'shovel snow')print(tasks) # ['shovel snow', 'groceries', 'post office', 'movie']
Similarly, we can even use insert() to take the place of append() and add a value to the end of a list.tasks = [
'groceries',
'post office',
'movie'
]tasks.insert(3, 'shovel snow')print(tasks) # ['groceries', 'post office', 'movie', 'shovel snow']
Two notes about that implementation. First, it’s probably not good practice to use an integer literal for something like this so we could refactor as such.tasks = [
'groceries',
'post office',
'movie'
]tasks.insert(len(tasks), 'shovel snow')print(tasks) # ['groceries', 'post office', 'movie', 'shovel snow']
Second, if we specify an index that is larger than “the next index”, empty indices are not added. The value is simply added to the end of the list.tasks = [
'groceries',
'post office',
'movie'
]tasks.insert(10, 'shovel snow')print(tasks) # ['groceries', 'post office', 'movie', 'shovel snow']
Conclusion
This simple method is easy to use—the key is remembering that it exists. One of the best ways to reinforce is by identifying real-world examples that resonate with your experiences.
What real-world uses do you have for the insert() method? Share them below and help out our Python community.
I hope you liked this article! Subscribe to be notified when I publish new articles or even better, support me by joining the Medium community as a paid subscriber.