Python pop is an inbuilt function. It is used to remove the latest (last) element from the python list. The python list pop takes one argument that is the index of the element. If the argument is not provided, then the default argument -1 will remove the last element from the list.
Table of Contents
Syntax of python pop:
List_name.pop(index)
Exception:
If the index is out of range, then it will throw an IndexError exception.
How to use pop in python?
To use the python pop, we need a list to remove elements from it. Pop functions do not work on any other data type in python. To remove the element call list.pop in python. Let’s see its demonstration with an example.
Example
from builtins import range
mylist = []
n = int(input("Enter how many elements"))
for i in range(0,n): #loop for storing values
x = int(input("Enter element"))
mylist.append(x)
print("The list is ",mylist)
print(mylist.pop()) #removing the last element of a list
print(mylist.pop(1)) #removing the third element of a list
print("After removing elements from the list", mylist)
Output
Enter how many elements5
Enter element1
Enter element2
Enter element3
Enter element4
Enter element5
The list is [1, 2, 3, 4, 5]
5
4
After removing elements from the list [1, 2, 3]
Example 2:
Not only integer values, but also we can use pop function to remove characters and words from the list.
mylist = ['red', 'blue', 'grey', 'yellow', 'pink', 'black', 'white']
print("The list is ",mylist)
print(mylist.pop()) #removing the last colour of a list
print(mylist.pop(4)) #removing the fourth colour of a list
print("After removing elements from list", mylist)
Output
The list is ['red', 'blue', 'grey', 'yellow', 'pink', 'black', 'white']
white
pink
After removing elements from list ['red', 'blue', 'grey', 'yellow', 'black']
FAQ’s
The pop function is used to remove the elements from the list. We can remove the specific element from the list using indexing. If the index is not provided, then the function automatically removes the last element from the list. We can easily use the pop python function using the dot (.) operator.