The Wayback Machine - https://web.archive.org/web/20240926232544/https://www.geeksforgeeks.org/python-set-pop-method/
Open In App

Python Set pop() Method

Last Updated : 06 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python set pop() removes any random element from the set and returns the removed element. In this article, we will see about the Python set pop() method.

Example

Input: {9, 1, 0}
Output: {9, 1}
Explanation: By using set pop() method, a random element 0 is removed from the set and remaining set is returned.

Python Set pop() Syntax

Syntax: set_obj.pop()

Parameter: set.pop() doesn’t take any parameter.

Return: Returns the popped element from the set

Set pop() Method in Python

Python Set pop() is a method in Python used to remove and return any random element from the set. As we all know, Sets are an unordered collection of unique elements, so there’s no guarantee which element will be removed and returned by the pop() method. If the set is empty, calling pop() will raise a KeyError.

Python Set pop() Method Example

Example 1: In this example, we are using the Python Set pop() method to pop any random element from the set and then print the remaining set.

Python3




s1 = {9, 1, 0}
s1.pop()
print(s1)


Output

{9, 1}

Example 2: In this example, we are using Python Set pop() to pop 3 elements from a set and then print the remaining set.

Python3




s1 = {1, 2, 3, 4}
print("Before popping: ",s1)
s1.pop()
s1.pop()
s1.pop()
 
print("After 3 elements popped, s1:", s1)


Output

Before popping:  {1, 2, 3, 4}
After 3 elements popped, s1: {4}

Exceptions while using Python Set pop() Method

In Python, TypeError is returned if the set is empty and we try to pop out the elements from the set. In this example, pop() method is used in an empty set to pop out the element but TypeError is returned as the result.

Python3




S = {}
 
# popping an element
print(S.pop())
 
print("Updated set is", S)


Output:

Traceback (most recent call last):
  File "/home/7c5b1d5728eb9aa0e63b1d70ee5c410e.py", line 6, in 
    print(S.pop())
TypeError: pop expected at least 1 arguments, got 0


Previous Article
Next Article

Similar Reads

List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)
Some of the list methods are mentioned in set 1 below List Methods in Python | Set 1 (in, not in, len(), min(), max()…) More methods are discussed in this article. 1. del[a : b] :- This method deletes all the elements in range starting from index 'a' till 'b' mentioned in arguments. 2. pop() :- This method deletes the element at the position mentio
4 min read
Python Dictionary pop() Method
Python dictionary pop() method removes and returns the specified element from the dictionary. Example: C/C++ Code # inializing dictionary student student = {"rahul":7, "Aditya":1, "Shubham":4} # priting original dictionary print(student) # using dictionary pop suspended = student.pop("rahul") # checking key o
4 min read
Python List pop() Method
Python list pop() function removes elements at a specific index from the list. Example [GFGTABS] Python fruits = ["apple", "mango", "cherry"] fruits.pop() print(fruits) [/GFGTABS]Output: ['apple', 'mango']Python List pop() Syntaxlist_name.pop(index)Parameterindex (optional) - The value at the index is popped out and re
5 min read
Python | Pandas Dataframe.pop()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas Pop() method is common in most of the data structures but pop() method is a little bit different from the rest. In a stack, pop do
2 min read
Python | Pandas Series.pop()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.pop() function returns the item corresponding to the passed index label. It als
2 min read
Wand push() and pop() in Python
We can use ImageMagick's internal graphic context stack to manage different styles and operations in Wand. There are total four push functions for context stack. push()push_clip_path()push_defs()push_pattern() push() function is used to grow context stack and pop() is another function and used to restore stack to previous push. Syntax : # for push(
2 min read
What Is Difference Between Del, Remove and Pop on Python Lists?
In python del is a keyword and remove(), pop() are in-built methods. The purpose of these three are same but the behavior is different remove() method delete values or object from the list using value and del and pop() deletes values or object from the list using an index. del Keyword: The del keyword delete any variable, list of values from a list
3 min read
How to create a pop up message when a button is pressed in Python - Tkinter?
In this article, we will see how to create a button and how to show a popup message when a button is pressed in Python. Tkinter is a standard Python Package for creating GUI applications. Tkinter may be a set of wrappers that implement the Tk widgets as Python classes. Python, when combined with Tkinter, provides a quick and straightforward way to
2 min read
IndexError: pop from Empty List in Python
The IndexError: pop from an empty list is a common issue in Python, occurring when an attempt is made to use the pop() method on a list that has no elements. This article explores the nature of this error, provides a clear example of its occurrence, and offers three practical solutions to handle it effectively. Here, we will see how to fix Pop From
3 min read
IndexError: pop from Empty Deque in Python
In Python, the IndexError: pop from an empty deque is an error that occurs when trying to use the pop() method on an empty deque. A deque (double-ended queue) is a versatile data structure that allows efficient addition and removal of elements from both ends. This article explores the causes of the error, provides examples of its occurrence, and of
4 min read
PyQt5 - Show pop up items of ComboBox when push button is pressed
In this article we will see how we make combo box to show its elements without clicking on it. In order to do this we will use showPopup method. Syntax : combo_box.showPopup() Argument : It takes no argument Action performed : It will show the pop up elements Steps for implementation : 1. Create a combo box 2. Add items to the combo box 3. Create a
2 min read
PyQt5 - Closing pop up items of ComboBox when push button is pressed
In this article we will see how we make combo box to hide its elements without clicking on it, in order to do this we will use hidePopup method. Syntax : combo_box.hidePopup() Argument : It takes no argument Action performed : It will hide the pop up elements Steps for implementation : 1. Create a combo box 2. Add items t the combo box 3. Create a
2 min read
PyQt5 QCalendarWidget - Enabling/Disabling Date Edit Pop-Up
In this article, we will see how we enable/ disable the date edit pop-up of the QCalendarWidget. By default date edit pop-up is enabled, The date edit is simpler in appearance than QDateEdit, but allows the user to navigate between fields using the left and right cursor keys, increment and decrement individual fields using the up and down cursor ke
2 min read
PyQt5 QCalendarWidget - Checking if Date Edit Pop-Up is enabled or disabled
In this article we will see how we check the date edit pop-up of the QCalendarWidget is enabled or not. By default date edit pop-up is enabled, The date edit is simpler in appearance than QDateEdit, but allows the user to navigate between fields using the left and right cursor keys, increment and decrement individual fields using the up and down cu
2 min read
PyQt5 QCalendarWidget - Setting Date Edit (Pop-Up) Accept Delay Property
In this article, we will see how we can set/change the date edit accept delay property of the QCalendarWidget. This property holds the time an inactive date edit is shown before its contents are accepted. If the calendar widget's date edit is enabled, this property specifies the amount of time (in milliseconds) that the date edit remains open after
2 min read
PyQt5 QCalendarWidget - Getting Date Edit (Pop-Up) Accept Delay
In this article, we will see how we can get the date edit accept delay property of the QCalendarWidget. This property holds the time an inactive date edit is shown before its contents are accepted. If the calendar widget's date edit is enabled, this property specifies the amount of time (in milliseconds) that the date edit remains open after the mo
2 min read
How to Create a pop up in pygame with pgu?
In this article, we will learn about how to create a pop-up in pygame with pgu in Python. PyGame The pygame library is an open-source Python module designed to assist you in creating games and other multimedia applications. Pygame, which is built on top of the highly portable SDL (Simple DirectMedia Layer) development library, can run on a variety
6 min read
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Python Set clear() Method
Python Set clear() method removes all elements from the set. Python Set clear() Method Syntax: Syntax: set.clear() parameters: The clear() method doesn't take any parameters. Return: None Time complexity : The time complexity of set.clear() function on a set with n element is O(n) . Example 1: Python Set clear() Method Example C/C++ Code test_set =
2 min read
Python Set isdisjoint() Method
Python set isdisjoint() function check whether the two sets are disjoint or not, if it is disjoint then it returns True otherwise it will return False. Two sets are said to be disjoint when their intersection is null. Python set isdisjoint() Method Syntax: Syntax: set1.isdisjoint(set2) Parameters: another set to compare withoran iterable (list, tup
2 min read
Python Set - intersection_update() Method
Python intersection_update() method is used to update a set with common elements only of all the sets passed in parameter of intersection_update() method. Python set intersection_update() Method Syntax: Syntax: set.intersection_update(set1,set2,set3,...........,set n) Parameters: One or more sets Return: None Note: To perform this function, we have
2 min read
Python Set - remove() method
Python remove() Function is a built-in method to remove elements from the set. remove() method takes exactly one argument. Syntax set.remove(element) If the element passed to the remove() is present in the set then the element will be removed from the set. If the element passed to the remove() is not present in the set then KeyError Exception will
1 min read
Python Set issubset() Method
Python set issubset() method returns True if all elements of a set A are present in another set B which is passed as an argument, and returns False if all elements are not present in Python. Python Set issubset() Method SyntaxSyntax: set_obj.issubset(other_set) Parameter: other_set: any other set to compare with.Return: bool Python set issubset() M
2 min read
Set add() Method in Python
The Python set add() method adds a given element to a set if the element is not present in the set in Python. Example: Add Element to an Empty setIt is used to add a new element to the empty set. [GFGTABS] Python GEEK = set() GEEK.add('s') print("Letters are:", GEEK) # adding 'e' again GEEK.add('e') print("Let
5 min read
Difference between Method Overloading and Method Overriding in Python
Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support
3 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
5 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
5 min read
Set Window Icon Text in PyQt5 | setWindowIconText() method
PyQt5 allows us to set the icon of window using setWindowIcon() method, on the other hand setWindowIconText() method is also present in it which allows us to set the text the icon. Although, it is not recommended to use as it has not any use, there was use in previous i.e old versions. It is now used to make the old source codes working. It was use
2 min read
PyQt5 – How to set tooltip duration for Label | setToolTipDuration method
In PyQt5, there is an option to set tool tip using setToolTip() method, The tooltip or infotip or a hint is a common graphical user interface element. It is used in conjunction with a cursor, usually a pointer. The user hovers the pointer over an item, without clicking it, and a tooltip may appear as a small "hover box" with information about the i
2 min read
PyQt5 – How to set minimum size of window | setMinimumSize method
We know that we can resize the window of PyQt5 application, but while shrinking the window size we can set minimum size so that it can't be shrank any more. In this article, we will see how to do this. In order to do this we will use setMinimumSize() method. Syntax : self.setMinimumSize(width, height) Argument : It takes two integer as argument. Ac
1 min read
Article Tags :
Practice Tags :