To insert an item into a list in Python, you can use the list insert() function. Pass the index and an object to insert to insert() to insert an object at a certain position.
lst = [0, 2, 4]
lst.insert(2, 3)
print(lst)
#Output:
[0, 2, 3, 4]
When working with collections of data, the ability to make changes and modify these collections easily is valuable.
One such case is if you want to insert an item into a list in your Python code.
To insert an item into a list in Python, you can use the list insert() function.
insert() takes in two parameters. The first parameter is the index of where you want to insert an object. The second parameter is the object you want to insert.
Below is a simple example of how you can insert an item into a list using Python.
lst = [0, 2, 4]
lst.insert(2, 3)
print(lst)
#Output:
[0, 2, 3, 4]
Inserting Multiple Items into List Using Python
If you want to insert multiple items into a list using Python, you can use the insert() function multiple times or you could use list slicing.
For example, let’s say you have a second list and want to insert this second list into the first list at the position 3.
list_1 = [0, 1, 2, 3, 6, 7]
list_2 = [4, 5]
You could use the insert() function in a loop and insert each item of the second list into the first list as shown below.
list_1 = [0, 1, 2, 3, 6, 7]
list_2 = [4, 5]
idx = 4
for item in list_2:
list_1.insert(idx, item)
idx = idx + 1
print(list_1)
#Output:
[0, 1, 2, 3, 4, 5, 6, 7]
One other way you could do this is with list slicing.
You can create two lists by slicing the list in two parts depending on where you want to make the insertion and then concatenate all of the lists together with +.
Below shows you how you can use list slicing to insert a list into a list using Python.
list_1 = [0, 1, 2, 3, 6, 7]
list_2 = [4, 5]
list_1 = list_1[:4] + list_2 + list_1[4:]
print(list_1)
#Output:
[0, 1, 2, 3, 4, 5, 6, 7]
Hopefully this article has been useful for you to learn how to insert into a list in Python.