In this article, we will show how to write a Python program to remove the first item or element from a given list with examples. There are multiple options to delete the first list element, and we show all the possibilities.
Python Program to Remove the First Element from a List Using Pop ()
The pop() function removes the list item based on the index value, and the first item holds 0 as the index. In the program below, we have created a simple integer list. Next, the a.pop(0) will remove the first element from the given list.
a = [2, 4, 6, 8, 10]
a.pop(0)
print(a)
[4, 6, 8, 10]
Using del statement
The del statement uses the index position, and based on the given position, this method will remove the element. In the below program, we pass the 0 as the index number because it represents the first element in a list, and the del statement will remove it.
a = [9, 2, 4, 6, 8, 10]
del a[0]
print(a)
[2, 4, 6, 8, 10]
Python Program to Delete the First Element from a List using remove() method
The remove() method removes the given element. And the below example passes 4 as the argument because it is the first element, so it removes the first list item.
a = [4, 6, 8, 10]
a.remove(4)
print(a)
[6, 8, 10]
Using list slicing
Apart from the above-mentioned options, you can try the list slicing technique. In the below program, (a = a[1:]) means we are slicing the existing list by omitting (removing) the first element and assigning it to a list.
a = [12, 14, 18, 20, 40]
a = a[1:]
print(a)
Using deque
In the program below, first, we import the deque() function from the collections library. Next, we used the popleft() to remove the first item or element from a given list. By default, the result will be deque, so we have to use the list() function to convert back.
from collections import deque
a = [12, 14, 18, 20, 40]
print(a)
b = deque(a)
b.popleft()
print(list(b))
[12, 14, 18, 20, 40]
[14, 18, 20, 40]