Python Set | pop()
This in-built function of Python helps to pop out elements from a set just like the principal used in the concept while implementing Stack. This method removes a random element from the set and returns the removed element. Unlike, a stack a random element is popped off the set.
Syntax:
# Pops a random element from S # and returns it. S.pop()
This is one of the basic functions of the set and accepts no arguments. The return value is the popped element from the set. Once the element is popped out of the set, the set loses the element and it is updated to a set without the element.
Examples:
Input : sets = {1, 2, 3, 4, 5} Output : 1 Updated set is {2, 3, 4, 5} Input : sets = {"ram", "rahim", "ajay", "rishav", "aakash"} Output : rahim Updated set is {'ram', 'rishav', 'ajay', 'aakash'}
# Python code to illustrate pop() method S = { "ram" , "rahim" , "ajay" , "rishav" , "aakash" } # Popping three elements and printing them print (S.pop()) print (S.pop()) print (S.pop()) # The updated set print ( "Updated set is" , S) |
Output:
rishav ram rahim Updated set is {'aakash', 'ajay'}
On the other hand, if the set is empty, then a TypeError is returned as shown by the following program.
# Python code to illustrate pop() method # on an empty set S = {} # Popping three elements and printing them print (S.pop()) # The updated set print ( "Updated set is" , S) |
Output:
No Output
Error:
Traceback (most recent call last): File "/home/7c5b1d5728eb9aa0e63b1d70ee5c410e.py", line 6, in print(S.pop()) TypeError: pop expected at least 1 arguments, got 0
Recommended Posts:
- Reading Python File-Like Objects from C | Python
- Python | Index of Non-Zero elements in Python list
- Important differences between Python 2.x and Python 3.x with examples
- Python | Convert list to Python array
- Python | Merge Python key values to list
- Python | Add Logging to a Python Script
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Add Logging to Python Libraries
- Python | Visualizing O(n) using Python
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- Any & All in Python
- zip() in Python
- set add() in python
- SQL using Python | Set 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.