In Python, the easiest way to prepend an item to a list is with the Python list insert() function.
list = [1,2,9,0,1,3]
list.insert(0,2)
#Output:
[2,1,2,9,0,1,3]
You can also use the deque appendleft function to prepend an item to a list.
from collections import deque
list = [1,2,9,0,1,3]
dequelist = deque(list)
dequelist.appendleft(2)
print(list(dequelist))
#Output:
[2,1,2,9,0,1,3]
In Python, lists are one of the most used data structures and allow us to work with collections of data easily. When working with lists, it is useful to be able to add or remove items from the list in an easy way.
With Python, we can easily prepend items to lists. There are multiple ways we can add items to the beginning of a list.
In Python, the easiest way to prepend an item to a list is with the Python list insert() function.
The insert() function takes in two arguments. The first argument is the position to insert an item, and the second argument is the item to insert.
To prepend to a list, we will insert at position ‘0’.
Below is an example of how to prepend an item to a list in Python.
list = [1,2,9,0,1,3]
list.insert(0,2)
#Output:
[2,1,2,9,0,1,3]
Using deque in Python to Remove the First Item from a List
Another way that you can prepend an item to a list is with the deque data structure from the Python collections module.
Deque, or doubly ended queue, is most useful if you need to quickly append or pop items from the beginning or end of your data. If you have a large collection of items, you deque can be faster than the similar list operations.
To add an item at the start of a list using deque, we convert the list to deque, use the appendleft() function, and then convert the result back to a list.
from collections import deque
list = [1,2,9,0,1,3]
dequelist = deque(list)
dequelist.appendleft(2)
print(list(dequelist))
#Output:
[2,1,2,9,0,1,3]
Using reverse() and append() to Add an Element at Beginning of a List in Python
One last method I’d like to share with you in this article is how to add an item at the beginning of a list using reverse() and append().
I wouldn’t recommend this as it’s not as efficient as the insert() method.
To use this way of adding an element at the the beginning of a list, you first reverse the list, use the append() function, and then reverse the list again.
Below is how to prepend an element to a list using reverse() and append().
list = [1,2,9,0,1,3]
list.reverse()
list.append(2)
list.reverse()
#Output:
[2,1,2,9,0,1,3]
Hopefully this article has been useful for you to learn how to prepend items to a list using Python.