Add an element at the front of a List in Python

This tutorial will discuss about unique ways to add an element at the front of a list in Python.

Table Of Contents

Using insert() function of List

Python List provides a function insert(index, element) to add a given element at the specified index in the list. It accepts two arguments,

  • Index position, at which we want to insert the element
  • Element to be inserted

It then adds the given element at the specified position in the list.

As the index starts from 0 in the list, so to add an element at the beginning of list, pass 0 as the first argument, and the element to be added as the second argument in the insert() function.

Advertisements

Let’s see the complete example,

listOfNumbers = [11, 12, 13, 14, 15, 16]

# element to be added in front of list
num = 99

# Add element at the start of a list
listOfNumbers.insert(0, num)

print(listOfNumbers)

Output

[99, 11, 12, 13, 14, 15, 16]

It added an element at the start of list in Python.

Using List Slicing

Using the [] operator, select the list range from 0 till 0 index number. Then assign a new element to this selected range. It will add the element at the front of list.

Let’s see the complete example,

listOfNumbers = [11, 12, 13, 14, 15, 16]

# element to be added in front of list
num = 99

# Add element at the start of a list
listOfNumbers[0:0] = [num]

print(listOfNumbers)

Output

[99, 11, 12, 13, 14, 15, 16]

It added an element at the beginning of list in Python.

Using astrik to unpack list and item at front

We will create a new list. First we will add the new element in this list, as the first element. After that, apply astrik operator on original list to unpack all elements of this list as individual items. Then add these unpacked items to the new list. In the end, assign this new list to the same original variable. This way a new element is added at the beginning of list in Python.

Let’s see the complete example,

listOfNumbers = [11, 12, 13, 14, 15, 16]

# element to be added in front of list
num = 99

# Add element at the start of a list
listOfNumbers = [num , *listOfNumbers]

print(listOfNumbers)

Output

[99, 11, 12, 13, 14, 15, 16]

It added an element at the start of list in Python.

Summary

We learned about three different ways to add an element at the front of a list in Python.

Advertisements

Thanks for reading.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top