Insert value at the beginning of the list in Python

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.

The letter ‘a’ is placed before number 1.

If you try to insert a list at the beginning, it will add the whole list, so it will work as the append function.

The list second_list was added at the beginning as a single element:

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:

If you run this code, you’ll notice that 7 and 8 were added separately at the beginning of the list.

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.

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:

Run the code, to see that this script works like the one with the insert function.