Python list pop() method is used to remove an element at the specified index and returns the removed element. If the index passed to this method is not in the range or does not exist in the list, it throws the IndexError: pop index out of range exception.
Syntax
list.pop(index)
Parameter
index(optional): It is the position where we need to remove the element from the list. If you don’t pass the index, then by default, the pop() function will remove the last element whose index would be -1.
Return value
This method returns the element present at the given index. This element is also removed from the list.
Example 1: How to Use list pop() Method
GoT = ['Daenerys', 'Jon', 'Tyrion']
removedItem = GoT.pop(1)
print (removedItem)
print(GoT)
Output
['Daenerys', 'Tyrion']
Example 2: Passing the negative index
GoT1 = ['Daenerys', 'Jon', 'Tyrion']
removedItem1 = GoT1.pop(-1)
print (removedItem1)
print(GoT1)
Output
Tyrion
['Daenerys', 'Jon']
Example 3: IndexError: pop index out of range
GoT2 = ['Daenerys', 'Jon', 'Tyrion']
removedItem2 = GoT2.pop(4)
print (removedItem2)
Output
Traceback (most recent call last):
File "app.py", line 2, in <module>
removedItem2 = GoT2.pop(4)
IndexError: pop index out of range
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.