This post will discuss how to insert an item at the front of a list in Python.

1. Using list.insert(i, x) function

You can use the list’s insert() function that inserts an item at the specified position. To insert an item x at the front of the list l, use l.insert(0, x). The complexity of this solution is O(n) as all items in the list gets shifted by one position to the right. Here n is the size of the list.

Download  Run Code

2. Transforming into list

Another approach is to convert the element to be inserted into the list and append it into the existing list. This solution creates a new list and often performs slower than the above solution.

Download  Run Code

 
Here’s another way of doing the same using slicing.

Download  Run Code

3. Iterable unpacking operator

You can also use the * iterable unpacking operator to insert an item at the front of a list. This feature was introduced in Python 3.5 with the acceptance of PEP 448 – Additional Unpacking Generalizations.

Download  Run Code

That’s all about inserting an item in front of a list in Python.