Remove first element from list in Python

In this post, we will see how to remove the first element from a list in python.


Using list.pop()

We can use list.pop() method to remove the first element from the list.

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:

List Of Fruits are: [‘Orange’, ‘Apple’, ‘Grapes’, ‘Mango’]
List Of Fruits after removing first element: [‘Apple’, ‘Grapes’, ‘Mango’]
Removed Fruit: Orange

pop will raise index error if the list is empty.


Using del statement

We can use del statement to remove first
element.

listOfFruits = ['Orange','Apple', 'Grapes','Mango'] print("List Of Fruits are:",listOfFruits) del listOfFruits[0] print("List Of Fruits after removing first element:",listOfFruits)

Output:

List Of Fruits are: [‘Orange’, ‘Apple’, ‘Grapes’, ‘Mango’]
List Of Fruits after removing first element: [‘Apple’, ‘Grapes’, ‘Mango’]

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.

listOfFruits = ['Orange','Apple', 'Grapes','Mango'] print("List Of Fruits are:",listOfFruits) listOfFruits = listOfFruits[1:] print("List Of Fruits after removing first element:",listOfFruits)

Output:

List Of Fruits are: [‘Orange’, ‘Apple’, ‘Grapes’, ‘Mango’]
List Of Fruits after removing first element: [‘Apple’, ‘Grapes’, ‘Mango’]

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.

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:

List Of Fruits are: [‘Orange’, ‘Apple’, ‘Grapes’, ‘Mango’]
List Of Fruits after removing first element: [‘Apple’, ‘Grapes’, ‘Mango’]

It throws index error in case the list is empty.

That’s all about how to remove first element from list in python

Related Posts

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.