How to Prepend to List in Python

This tutorial covers how to prepend elements to a list in Python.

 

 

Prepend to List in Python using list.insert()

The easiest way to prepend an element to a list is to use the built-in Python insert() method. Pass the list before the method and specify the index as the first argument and the value of the element as the second. Here is an example:

 

items = [2, 3, 4]

items.insert(0, 1)

print(items)
[1, 2, 3, 4]

 

To insert at the beginning of any list we use 0 as that is where the index starts.

 

What's nice about inset() is that it can be used to prepend elements to a list by counting the length of the list to determine the next index like this:

 

items = [2, 3, 4]

items.insert(len(items) -1, 1)

print(items)
[2, 3, 4, 1]

 

Prepend to a Python List Using collections.deque.appendleft()

 

Another way to prepend to lists in Python is to use the .deque.appendleft() method from the collections package.

 

from collections import deque

items = [2, 3, 4]

res = deque(items)
res.appendleft(1)

print(list(res))
[1, 2, 3, 4]

 

The advantage of using this function is it can perform prepend operations faster. On the other hand, it's a bit more clunky to implement and you have to load another package into your program.