How to Use the insert() Function in Python?

In this tutorial, I will explain how to use the insert() function in Python. As a Python developer, while working on a project for New York clients, I came across a scenario where I needed to use the insert() and I explored more about the insert() function. Let us learn more about this topic today.

insert() Function in Python

The insert() method is a built-in Python function that allows you to add an element at any specified position in a list. The general syntax is:

list.insert(index, element)

Where:

  • list is the name of the list you want to modify
  • index is the position where you want to add the new element (an integer)
  • element is the item you want to insert into the list

The insert() method modifies the original list in place by adding the element at the given index. All the items after that index are shifted to the right by one position to make space for the new element.

Python’s insert() method is part of its standard library, so you don’t need to import any modules to use it. It’s a convenient way to add items to lists at specific locations.

Read Python Lists of Floats

Example 1: Insert an Element at the beginning of a List

Let’s say we have a list of the largest cities in the USA by population:

cities = ['New York', 'Los Angeles', 'Chicago', 'Houston'] 

If we want to add ‘Phoenix’ at the beginning of this list, we can use insert() with an index of 0:

cities.insert(0, 'Phoenix')
print(cities)

Output:

['Phoenix', 'New York', 'Los Angeles', 'Chicago', 'Houston']

I have executed the above example code and added the screenshot below.

insert() Function in Python

As you can see, ‘Phoenix’ was inserted at index 0, and the other cities were shifted to the right. Using an index of 0 with insert() always adds the new element at the very beginning of the list.

Check out How to Insert a Python Variable into a String

Example 2: Insert an Element in the Middle of a List

We can also use insert() to add an element somewhere in the middle of a list. Let’s insert ‘Philadelphia’ between ‘Los Angeles’ and ‘Chicago’:

cities = ['New York', 'Los Angeles', 'Chicago', 'Houston']
cities.insert(2, 'Philadelphia') 
print(cities)

Output:

['New York', 'Los Angeles', 'Philadelphia', 'Chicago', 'Houston'] 

I have executed the above example code and added the screenshot below.

Use the insert() Function in Python

Here we used an index of 2 to add ‘Philadelphia’ at the 3rd position (remember indexes start at 0). ‘Chicago’ and ‘Houston’ were shifted over to make room.

Read Python Add String to List

Example 3: Insert an Element at the End of a List

To add an element at the very end of a list with insert(), use an index equal to the length of the list. Let’s add ‘San Antonio’ at the end:

cities = ['New York', 'Los Angeles', 'Chicago', 'Houston']
cities.insert(len(cities), 'San Antonio')
print(cities)  

Output:

['New York', 'Los Angeles', 'Chicago', 'Houston', 'San Antonio']

I have executed the above example code and added the screenshot below.

How to Use the insert() Function in Python

By using len(cities) as the index, we ensure the new element is added after the last item in the list. This has the same effect as using the append() method.

Check out How to Convert List to Set Python

Example 4: Insert Multiple Elements into a List

We can use a loop with the insert() method to add multiple elements at specific indexes in a list. Let’s insert 3 cities into our list at positions 2, 4, and 6:

cities = ['New York', 'Los Angeles', 'Chicago', 'Houston']

new_cities = ['Phoenix', 'Philadelphia', 'San Antonio']
indexes = [2, 4, 6]

for i in range(len(new_cities)):
    cities.insert(indexes[i], new_cities[i])

print(cities)

Output:

['New York', 'Los Angeles', 'Phoenix', 'Chicago', 'Philadelphia', 'Houston', 'San Antonio'] 

This code uses parallel lists new_cities and indexes to specify the elements to insert and their positions. It loops through them, inserting each new city at the corresponding index.

Read Python Append List to List Without Nesting

Deal with IndexError

One potential issue when using insert() is triggering an IndexError by specifying an invalid index. This can happen if the index is greater than the length of the list.

For example:

cities = ['New York', 'Los Angeles', 'Chicago', 'Houston']
cities.insert(10, 'Phoenix') 

This raises:

IndexError: list index out of range

To avoid this error, make sure to only use indexes between 0 and the length of the list. If you need to add an element at the end, you can use len(list) the index or the append() method instead.

Check out Python Program to Swap Two Elements in a List

Difference between insert() and append()

Both insert() and append() add elements to a list, but in different ways:

  • insert(index, element) adds the element at the specified index, shifting all elements after it to the right
  • append(element) adds the element at the very end of the list without affecting the positions of other elements

Here’s an example showing the difference:

cities = ['New York', 'Los Angeles', 'Chicago', 'Houston']

cities.insert(2, 'Phoenix')
print(cities) 
# Output: ['New York', 'Los Angeles', 'Phoenix', 'Chicago', 'Houston']

cities.append('Philadelphia')  
print(cities)
# Output: ['New York', 'Los Angeles', 'Phoenix', 'Chicago', 'Houston', 'Philadelphia']

So use insert() when you need to add elements at specific positions and append() when you just want to add them to the end of the list.

Read How to Prepend to a List in Python

Conclusion

In this tutorial, I have explained how to use the insert() function in Python. I discussed the insert() function in Python , examples of inserting an element at the beginning of a list, middle of the list, end of a list and inserting multiple elements into a list. I also showed how to deal with IndexError, and the difference between insert() and append().

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.