As you already know a list is a data structure that allows you to store multiple objects in a single variable. There are many functions in the Python list for manipulation. The pop() function is one of them. In this tutorial, you will learn how to remove the element from the list using the pop function in Python list.
Syntax for the pop function
In Python, the pop() function is used to remove and return an element from a list. It operates on a list and takes an optional argument. The argument is the index of the element that you want to remove. If no index is specified, pop() will remove the last element of the list.
Example of Pop Function in Python List
Let’s learn all the examples for implementing the pop function. But before creating a sample list.
Create a list
my_list = [10, 20, 30, 40, 50]
Example 1: Use the pop() function without passing index
If you don’t pass the index as an argument for the pop function then it will remove the last element from the list.
popped_element = my_list.pop()
When you run the code you will see that popped_element will be equal to 50. Lastly, my_list will contain only [10, 20, 30, 40] only as the 50 element is removed.
Example 2: Remove the specific element using index
You can also use the pop() function with an index to remove and return a specific element from the list. For example, if you want to remove and return the element at index 1 (which is in this case(20 ). To do so you will use the below lines of code.
popped_element = my_list.pop(3)
Now, popped_element will be equal to 4, and my_list will be [10,30, 40].
Example 3: Passing the index out of range
If you try to pop() an index that is out of range (i.e., an index that doesn’t exist in the list), you will get an IndexError. You will get the error when you run the below lines of code.
popped_element = my_list.pop(5) # IndexError
Example 4: Use the popped element
You can also use the pop() function to remove and return an element from the list. After that, you can use that element in your code as needed.
my_list = [10, 20, 30, 40, 50] popped_element = my_list.pop(2) # Removes and returns the element at index 2 (which is 3) print("Popped element:", popped_element) print("Updated list:", my_list)
Popped element: 30 Updated list: [10, 20, 40, 50]
The pop() function in the Python list is a very useful function. It is because using it you can remove the element from the list as well as store the popped element in a variable. Thus it allows you to use it anywhere as per need. The above is an example of how to implement the pop() function.