Remove first item from a Python list
This post will discuss how to remove the first item from a list in Python.
1. Using list.pop() function
The simplest approach is to use the list’s pop([i]) function, which removes and returns an item present at the specified position in the list.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5] first = a.pop(0) print(first) # 1 print(a) # [2, 3, 4, 5] |
The pop([i]) function raises an IndexError if the list is empty as it tries to pop from an empty list.
2. Using list.remove() function
Another approach is to use the list’s remove(x) function, which removes the first item from the list, which matches the specified value. The idea is to pass the value of the list’s first item to it, as shown below:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5] a.remove(a[0]) print(a) # [2, 3, 4, 5] |
The remove() function raises an IndexError if the list is empty since it tries to access the list’s index, which is out of range.
3. Using Slicing
We know that we can slice lists in Python. We can use slicing to remove the first item from a list. The idea is to obtain a sublist containing all items of the list except the first one. Since slice operation returns a new list, we have to assign the new list to the original list. This can be done using the expression l = l[1:], where l is your list.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5] a = a[1:] print(a) # [2, 3, 4, 5] |
Note that this function doesn’t raise any error on an empty list but constructs a copy of the list, which is not recommended.
4. Using del statement
Another way to remove an item from a list using its index is the del statement. It differs from the pop() function as it does not return the removed item. Unlike the slicing function, this doesn’t create a new list but modifies your original list.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5] del a[0] print(a) # [2, 3, 4, 5] |
The above code raises an IndexError if the list is empty since it tries to access index 0 of the list, which is out of range.
That’s all about removing the first item from a list in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)