How to prepend to list?
Python does not offer a prepend function to add content at the start of the list. However, there are several ways to achieve the result prepending a list with other functions. To prepend is the opposite of append, which can be done by using the append() function for list data structures. To prepend use one of the following ways.
The options are in summary:
- prepend by using insert() method
- prepend by creating a new list
- prepend by slicing
- prepend by using deque
prepend by using insert() method
To prepend to a list we can use the insert() method of lists and passing the index argument 0. The passed value will then be inserted at the index 0, which is the start at the list.
# prepend using insert()
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# insert integer 0 at position 0
myList.insert(0, 0)
print(myList)
The integer 0 is inserted at position 0, the start of the list. The result is printed.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
prepend by creating a new list
This option is not exactly prepending to an existing list, but it yields the same result. Instead of changing the list, create a new list by combining the value and the old list.
# prepend by creating a new list
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
myNewList = [0] + myList
print(myNewList)
The integer 0 is added at the start of the new list and therefore prepended to the new list.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
prepend by slicing
Slicing is a very common operation in Python and arguable this is the most pythonic way to prepend to a list. Start the slice at index 0 and then insert the new value as list at the start of the old list.
# prepend by slicing
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
myList[:0] = [0]
print(myList)
The new value is sliced into the old list at position 0, the beginning of the list.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
prepend by using collections.deque
Deque is a doubly ended queue and can be appended from both sides. Use the appendleft() method to add a value at the left side, which is the position 0 of our list.
# prepend using collections.deque
from collections import deque
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
myList = deque(myList)
myList.appendleft(0)
myList = list(myList)
print(myList)
The list is turned into deque. Then the element 0 is added at the left side. And finally the deque is turned into a list again.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]