Tue Jun 21 2022·2 min read
Photo by Adrian Infernus
list.insert() method to append an item to the front of a list, e.g.
my_list.insert(0, value). The
insert() method will insert the provided value
at the front (position
0) of the list.
my_list = [20, 30] value = 10 my_list.insert(0, value) print(my_list) # 👉️ [10, 20, 30]
We used the
list.insert() method to add an item to the front of a list.
The list.insert method inserts an item at a given position.
The method takes the following 2 parameters:
|index||The index of the element before which to insert|
|item||The item to be inserted at the given index|
list.insert() method is very convenient and quite fast.
Note that the
insert() method mutates the original list in place.
An alternative approach is to use the addition (+) operator.
To add a value to the front of a list in Python:
my_list = [20, 30] value = 10 new_list = [value] + my_list print(new_list) # 👉️ [10, 20, 30]
The addition (+) operator can be used to join two lists into a single list.
print( + [20, 30]) # 👉️ [10, 20, 30]
Make sure to wrap the value you want to add to the front of the list in square brackets and place it on the left-hand side of the addition operator.
list.insert()method, but it doesn't mutate the original list, it returns a new list.
Alternatively, you can use an asterisk
* to unpack the list items into a new
list, after the specific value.
my_list = [20, 30] value = 10 new_list = [value, *my_list] print(new_list) # 👉️ [10, 20, 30]
* unpacks the items of the list into the new list.
This approach also doesn't mutate the original list.