Insert an item in front of a Python list
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.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': lst = [2, 3, 4, 5] val = 1 lst.insert(0, val) print(lst) # prints [1, 2, 3, 4, 5] |
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.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': lst = [2, 3, 4, 5] val = 1 lst = [val] + lst print(lst) # prints [1, 2, 3, 4, 5] |
Here’s another way of doing the same using slicing.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': lst = [2, 3, 4, 5] val = 1 lst[:0] = [val] print(lst) # prints [1, 2, 3, 4, 5] |
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.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': lst = [2, 3, 4, 5] val = 1 lst = [val, *lst] print(lst) # prints [1, 2, 3, 4, 5] |
That’s all about inserting an item in front of a list in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)