C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python Set pop() MethodPython pop() method pops an element from the set. It does not take any argument but returns the popped element. It raises an error if the element is not present in the set. See the examples and signature of the method is given below. Signaturepop() ParametersNo parameter. ReturnIt returns deleted element or throws an error if the set is empty. Let's see some examples of pop() method to understand it's functionality. Python Set pop() Method Example 1A simple example to use pop() method which removes an element and modifies the set. # Python set pop() Method # Creating a set set = {1,2,3,4,5} # Displaying elements print(set) # Calling function el = set.pop() print("Element popped:",el) print("Remaining elements: ",set) el = set.pop() print("Element popped:",el) print("Remaining elements: ",set) el = set.pop() print("Element popped:",el) print("Remaining elements: ",set) el = set.pop() print("Element popped:",el) print("Remaining elements: ",set) Output: {1, 2, 3, 4, 5} Element popped: 1 Remaining elements: {2, 3, 4, 5} Element popped: 2 Remaining elements: {3, 4, 5} Element popped: 3 Remaining elements: {4, 5} Element popped: 4 Remaining elements: {5} Python Set pop() Method Example 2If the set is empty, it throws an error KeyError to the caller function. See the example. # Python set pop() Method # Creating a set set = {1,2} # Displaying elements print(set) # Calling function el = set.pop() print("Element popped:",el) print("Remaining elements: ",set) el = set.pop() print("Element popped:",el) print("Remaining elements: ",set) el = set.pop() print("Element popped:",el) print("Remaining elements: ",set) Output: {1, 2} Element popped: 1 Remaining elements: {2} Element popped: 2 Remaining elements: set() Traceback (most recent call last): File "main.py", line 13, in Python Set pop() Method Example 3This example contains adding and poping elements in sequence to describe the functioning. # Python set pop() Method # Creating a set set = {1,2} # Displaying elements print(set) # Calling function el = set.pop() print("Element popped:",el) print("Remaining elements: ",set) set.add(4) el = set.pop() print("Element popped:",el) print("Remaining elements: ",set) set.add(5) el = set.pop() print("Element popped:",el) print("Remaining elements: ",set) Output: {1, 2} Element popped: 1 Remaining elements: {2} Element popped: 2 Remaining elements: {4} Element popped: 4 Remaining elements: {5}
Next TopicPython Set
|