Open In App

Prepend Elements to Lists in Python

Last Updated : 17 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, prepending means adding elements to the beginning of a list. We can think of it as putting something at the front of a queue. In this article, we will explore various methods to prepend elements to lists in Python. The insert() method to add an element at a specific position in a list. To add an element at the beginning, we can specify position 0.

Python
a = [2, 3, 4]

# Adds 1 at the beginning of the list
a.insert(0, 1)
print(a)  

Output
[1, 2, 3, 4]

Other methods that we can use to prepend elements to a list are:

Using + Operator

Another simple method is to use the + operator to concatenate lists. We can create a new list with the element to be prepended and then join it with the original list.

Python
a = [2, 3, 4]
b = [1]

# Adds 1 at the beginning by joining two lists
a = b + a  
print(a)

Output
[1, 2, 3, 4]

Using collections.deque

This is one of the most efficient ways to prepend elements if we are working with lists that change frequently. The deque (double-ended queue) is optimized for appending and prepending elements quickly.

Python
from collections import deque

a = deque([2, 3, 4])

# Adds 1 at the beginning of the deque
a.appendleft(1)  
print(a)  

Output
deque([1, 2, 3, 4])

Next Article
Article Tags :
Practice Tags :

Similar Reads