Python includes by default a whole series of methods that simplify and speed up the execution of programs. Among these, we can note the Python insert() method which allows you to insert a single element into an existing Python List. If you want to add multiple items to this list at once, or just add individual items at the end, the Python extend and Python append methods are preferable.
Syntax, parameters and operation of insert() in Python¶
The Python insert method is constructed with two parameters: the element to insert and the index (the location) where this element must be inserted. As Python lists are heterogeneous, this element can be data of any type (e.g. a list, an integer, etc.). However, the index must be indicated as an integer. The following line of code illustrates the syntax insert in Python:
ingredients.insert(1, "sucre")
Python
In this example, the character string (or “string” in English) "sucre"
is inserted at position 1 in the list ingredients
. The index where the element is inserted constitutes the first argument, the element itself the second. As usual, both parameters can be inserted directly or defined as variables before calling the method. Let’s see how in the following example:
ingredients = ["farine", "œufs", "beurre"]
ingredients.insert(0, "sucre")
print(ingredients) # Sortie : [‘sucre’, ‘farine’, ‘œufs’, ‘beurre’]
Python
In this example, we complete a list of pastry ingredients with additional ingredients, inserted respectively at indexes 0 and 2. It is important to note that theindexing in Python starts at 0, as in most other programming languages. This means that the first element is given index 0, the second element is given index 1 and so on. When an element is inserted into a Python list with insert()
, the program will of course make room for it. To do this, the element already present at the index and all its successors are moved one position to the right.
If the specified index is outside the valid range in the list (larger than the number of elements in the list, for example), the element will simply be inserted at the end of the list. In this case, insert()
behaves exactly like the Python append() method. However, if we associate a negative index with an element, it will be interpreted as distance from end of list. For example, -1
would correspond to the penultimate element, -2
to the antepenultimate, etc. Here is an example that illustrates these two properties:
ingredients.insert(10, "levure")
print(ingredients) # Sortie : [‘sucre’, ‘farine’, ‘œufs’, ‘beurre’, ‘levure’]
ingredients.insert(-2, "sel")
print(ingredients) # Sortie : [‘sucre’, ‘farine’, ‘œufs’, ‘sel, ‘beurre’, ‘levure’]
Python
Are you looking to get your website or web application online quickly, easily and hassle-free? So use Git with Deploy Now by IONOS, a platform designed for you!
Alternatives to Python insert()¶
Depending on the function you need, there are several Python operators that can be used as variations of the method insert()
. Here are two.
Index Operator¶
The index operator allows you to read or replace an element at a given index in a list. It is therefore possible to replace one element of a list by another with this index operator. Here is the syntax for this method in the following example:
print(ingredients) # Sortie : [‘sucre’, ‘farine’, ‘œufs’, ‘sel, ‘beurre’, ‘levure’]
ingredients[2] = "bicarbonate"
print(ingredients) # Sortie : [‘sucre’, ‘farine’, ‘bicarbonate’, ‘sel, ‘beurre’, ‘levure’]
Python
Slice Operator¶
You may also not want to remove an item from your list, or even want to insert several items at the same time in the middle of your list. In this case, it is best to use the Slice operator. Unlike the Index operator, the Slice operator does not return a single element of a list, but a subsequence of the list. Thus, we could remove from our list ingredients
the elements of indices 3 to 5 and thus obtain the subsequence [‘sel’, ‘beurre’, ‘levure chimique’]
. The following example illustrates how to insert as many elements as you want in the middle of your list with the Slice operator:
inserer = ["plus de sucre", "encore plus de sucre"]
ingredients = ingredients[:3] + inserer + ingredients[3:]
print(ingredients)
Python
In this case, the list inserer
was added in the middle of the list ingredients
. For this, we first took all the elements of ingredients
up to index 3 with the Slice operator and we concatenated them with inserer
. Then we took all the elements of ingredients
from index 3 and concatenated our list with it. Finally we crushed ingredients
with the list resulting from this double concatenation.
It’s important to note that this solution requires a lot of writing. Indeed, with it the whole list is overwritten. Take this into account if your program needs to be very efficient and if you handle lists with many entries.