Append an item to the front of a list in Python

avatar

Borislav Hadzhiev

Tue Jun 21 20222 min read

Append an item to the front of a list in Python #

Use the 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.

main.py
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.

Python indexes are zero-based, which means that the first item in a list has an index of 0.

The list.insert method inserts an item at a given position.

The method takes the following 2 parameters:

NameDescription
indexThe index of the element before which to insert
itemThe item to be inserted at the given index

Using the 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:

  1. Wrap the value in square brackets to make it an element of a list.
  2. Use the addition operator to add the list containing the value and the original list.
  3. The first item in the new list will be the provided value.
main.py
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.

main.py
print([10] + [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.

This approach is a bit slower than using the 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.

main.py
my_list = [20, 30] value = 10 new_list = [value, *my_list] print(new_list) # 👉️ [10, 20, 30]

The asterisk * unpacks the items of the list into the new list.

This approach also doesn't mutate the original list.

Use the search field on my Home Page to filter through my more than 1,000 articles.