Pop is a handy method for removing and retrieving the first element from list.

This article will show you how to use the pop() function to remove and retrieve the first item in a list in Python, which can be extremely useful when working with various types of data structures lik …

Updated October 2, 2023

This article will show you how to use the pop() function to remove and retrieve the first item in a list in Python, which can be extremely useful when working with various types of data structures like deque, stacks, etc.

Python has a built-in pop method for lists that we can use to remove and retrieve the first element from a list. The pop() method is an inbuilt function in python which is used to remove the last item or a specified item from the list. But if no index is passed then it will return the first item in the list and also remove it from the list.

Here’s an example of how you might use this:

# Initialize our list
my_list = [1, 2, 3, 4, 5]

# Pop the first element off the list
first_element = my_list.pop(0)
print("First Element: ", first_element)   # Outputs "First Element:  1"

You can see that after the pop() call, our list no longer contains the number 1, but the variable ‘first_element’ still holds a reference to it. If you need to retrieve the first element of your list again later, you’d have to call my_list[0] or use another pop(0) method. But using pop() method for retrieving first element is more efficient and also safer as we are sure that after popping once the element won’t be available at index 0 again.

Hey! Do you love Python? Want to learn more about it?
Let's connect on Twitter or LinkedIn. I talk about this stuff all the time!