Python popitem() function

The popitem() function is used to remove the last item from a specified dictionary. For example:

x = {"Date": "02", "Day": "Thu", "Month": "Dec", "Year": "2021"}
print(x)

x.popitem()
print(x)

The output will be:

{'Date': '02', 'Day': 'Thu', 'Month': 'Dec', 'Year': '2021'}
{'Date': '02', 'Day': 'Thu', 'Month': 'Dec'}

Note: If you heard about popitem(), it removes an item from a specified dictionary, randomly, instead of the last one. Then let me tell you, yes, it was true, but before Python Version 3.7.

Python popitem() function syntax

The syntax of the popitem() function in Python is:

dictionaryName.popitem()

It returns the removed item.

Python popitem() function example

Here is an example of popitem() in Python:

x = {"Date": "02", "Day": "Thu", "Month": "Dec", "Year": "2021"}
print(x)

print("\nThe item that is going to remove is:", x.popitem())
print("\nNow the dictionary is:")
print(x)

The snapshot given below shows the sample output produced by this Python program, demonstrating the popitem() function:

python popitem function

Advantages of the popitem() function in Python

Disadvantages of the popitem() function in Python

Python Online Test


« Previous Function Next Function »


Liked this post? Share it!