In this post, we will see how to remove the first element from a list in python.
Table of Contents
Using list.pop()
We can use list.pop() method to remove the first element from the list.
1 2 3 4 5 6 7 |
listOfFruits = ['Orange','Apple', 'Grapes','Mango'] print("List Of Fruits are:",listOfFruits) removedFruit = listOfFruits.pop(0) print("List Of Fruits after removing first element:",listOfFruits) print("Removed Fruit:",removedFruit) |
Output:
pop will raise index error if the list is empty.
Using del statement
We can use del statement to remove first
element.
1 2 3 4 5 6 |
listOfFruits = ['Orange','Apple', 'Grapes','Mango'] print("List Of Fruits are:",listOfFruits) del listOfFruits[0] print("List Of Fruits after removing first element:",listOfFruits) |
Output:
It raises IndexError if list is empty as it is trying to access an index that is out of range.
Using slicing
We can also use slicing to remove the first element. We can get a sublist
of elements except the first element.
1 2 3 4 5 6 |
listOfFruits = ['Orange','Apple', 'Grapes','Mango'] print("List Of Fruits are:",listOfFruits) listOfFruits = listOfFruits[1:] print("List Of Fruits after removing first element:",listOfFruits) |
Output:
Please note that slicing operation will return a new list, so this method is not recommended. We can obviously assign the list to the old one.
Using remove()
We can also use list’s remove()
method to remove first element from the list. remove method takes value as argument and removes the first occurrence of value specified.
1 2 3 4 5 6 |
listOfFruits = ['Orange','Apple', 'Grapes','Mango'] print("List Of Fruits are:",listOfFruits) listOfFruits.remove(listOfFruits[0]) print("List Of Fruits after removing first element:",listOfFruits) |
Output:
It throws index error in case the list is empty.
That’s all about how to remove first element from list in python