The append method adds an element at the end of the list. No function will add an element at the beginning of a list, but there is a method called insert, that you can use to insert an element in any place you want.
Insert function
Indexing in Python starts from 0, that’s why you can use this number to place an object at the first position of a list, using the insert function.
1 2 3 |
my_list = [1, 2, 3, 4, 5, 6] my_list.insert(0, 'a') print(my_list) |
The letter ‘a’ is placed before number 1.
1 |
['a', 1, 2, 3, 4, 5, 6] |
If you try to insert a list at the beginning, it will add the whole list, so it will work as the append function.
1 2 3 4 |
my_list = [1, 2, 3, 4, 5, 6] second_list = [7, 8] my_list.insert(0, second_list) print(my_list) |
The list second_list was added at the beginning as a single element:
1 |
[[7, 8], 1, 2, 3, 4, 5, 6] |
The (+) operator
If you want to extend elements as the extend function does, but at the beginning of a list and not at the end, you can use this code:
1 2 3 4 |
my_list = [1, 2, 3, 4, 5, 6] second_list = [7, 8] my_list = second_list + my_list print(my_list) |
If you run this code, you’ll notice that 7 and 8 were added separately at the beginning of the list.
1 |
[7, 8, 1, 2, 3, 4, 5, 6] |
Slicing
The third way you can use to add elements at the beginning of a list is by slicing. In this case, you are going to add elements to the list from beginning to 0.
1 2 3 4 |
my_list = [1, 2, 3, 4, 5, 6] second_list = [7, 8] my_list[:0] = second_list print(my_list) |
The code will add all elements separately at the beginning of the list. It’s important to add a colon before 0, otherwise, it will add the second list as a single element. Take a look:
1 2 3 4 |
my_list = [1, 2, 3, 4, 5, 6] second_list = [7, 8] my_list[0] = second_list print(my_list) |
Run the code, to see that this script works like the one with the insert function.
1 |
[[7, 8], 2, 3, 4, 5, 6] |