Tutorial Study Image

Python pop()

The pop() function in python helps to remove and return a specified key element from the dictionary. The return value of this method should be the value of the removed item.


dictionary.pop(key[, default]) #where key which is to be searched
 

pop() Parameters:

The pop() function takes two parameters. Python also supports list pop, which removes the specified index element from the list. If an index is not provided, the last element will be removed. 

Parameter Description Required / Optional
key The key name of the item you want to remove Required
default  A value to be return if the specified key does not exist. Optional

pop() Return Value

The return value of the pop() depends on the arguments given.

Input Return Value
key exists removed/popped element from the dictionary
key not exist default value
key not exist & default value not given KeyError exception

Examples of pop() method in Python

Example 1: How to pop an element from the dictionary in Python


# random fruits dictionary
fruits = { 'mango': 5, 'banana': 4, 'strawberry': 3 }

key = fruits.pop('mango')
print('The popped item is:', key)
print('The dictionary is:', fruits)
 

Output:


The popped item is: 5
The dictionary is: {'banana': 4, 'strawberry': 3}

Example 2: How to pop an element not present in the dictionary


# random fruits dictionary
fruits = { 'mango': 5, 'banana': 4, 'strawberry': 3 }

key= fruits.pop('orange')
 

Output:


KeyError: 'orange'

Example 3: How to pop an element not present in the dictionary provided with defalt value


# random fruits dictionary
fruits = { 'mango': 5, 'banana': 4, 'strawberry': 3 }

key = fruits.pop('orange', 'grapes')
print('The popped item is:', key)
print('The dictionary is:', fruits)
 

Output:


The popped item is: grapes
The dictionary is: { 'banana': 4,'mango': 5,'strawberry': 3