Python List pop() Method

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() MethodVisual Representation of 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 indexPassing negative index in list.pop method

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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.