How to Prepend to a List in Python

Usually, we use the append() operation to append any item at the end of the list. However, in some cases, it is required to append an element at the beginning of a list which is known as prepending an element to a list. In this tutorial, we will learn about how to prepend to a list in Python. We will learn different techniques along with examples to get a better understanding.

If you want to learn more about lists, See Python List Tutorials

Method 1: Using Slicing Operation

The slicing operation can be used to perform this particular task. In this method, we assign the desired item to the 0th slice of the list. For example

# initializing list 

x = ['b',0.5, 1,'d', 22]
  
# using slicing method to append at beginning

x[:0] = ['a']
           
# printing  list 

print(x)

Output:

['a', 'b', 0.5, 1, 'd', 22]

In this example, using the slicing technique, we appended an item ‘a’ at the beginning of the list at the 0th index.

Method 2: using insert() function

One other possible solution is to use the insert() function. The insert function takes two parameters as an input which are the index and the item that you want to insert. On running the code, it inserts that item at the specified index. For example

# initializing list 

x = [8, 2, 9, 10, 7]
  
# using insert() to append at beginning

x.insert(0, 4)
           
# printing  list 

print(x)

Output:

[4, 8, 2, 9, 10, 7]

If you want to print the list without square brackets, check this tutorial. This method is only efficient for small lists. In order to insert an item in the beginning, we need to move down all the elements by one. Therefore, this method is inefficient for large lists.

Method 3: using ‘+’ operator

Another easiest solution is to create another list consisting of the desired item that you want to prepend at the first index. Then combine the two lists using the ‘+’ operator. The following code snippet shows the implementation.

# initializing list 

x = [8, 2, 9, 10, 7]
  
# using '+' operator to append at beginning

x = [4] + x
           
# printing  list 

print(x)

Output:

[4, 8, 2, 9, 10, 7]

You can also add a character using the ‘+’ operator. Let’s see another example demonstrating the insertion of a character in a list of strings.

# initializing list 
x = ['b','c','d','e']
  
# using '+' operator to append at beginning
x = ['a'] + x
           
# printing  list 
print(x)

Output:

['a', 'b', 'c', 'd', 'e']

In short, in this article, we have learned the three different methods by which we can add any item at the beginning of a list. If you have any queries or you want us to cover any specific topic, please let us know in the comments. Your suggestions would be highly appreciated. Contact us. See more Python Tutorials

Leave a Comment

Your email address will not be published. Required fields are marked *