Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python Set pop() method



The Python Set pop() method is used to remove and return an arbitrary element from a set. If the set is empty it raises a 'KeyError'.

This method can be useful when we need to process or manipulate set elements individually without concern for order. Unlike lists, sets are unordered collections so the pop() method does not specify which element will be removed. This method modifies the original set by removing the returned element. It's efficient for tasks where the specific element to be removed is not important.

Syntax

Following is the syntax and parameters of Python Set pop() method −

set.pop()

Parameter

This method does not accept any parameters.

Return value

This method returns the removed element.

Example 1

Following is the example shows the basic usage of the pop() method to remove and return the popped element from the set −

# Define a set
sample_set = {1, 2, 3, 4, 5}

# Pop an element
popped_element = sample_set.pop()

# Print the popped element and the updated set
print("Popped Element:", popped_element)  
print("Updated Set:", sample_set)           

Output

Popped Element: 1
Updated Set: {2, 3, 4, 5}

Example 2

This example shows the usage of the pop() method in a loop to remove and printed the popped elements and updated set −

# Define a set
sample_set = {1, 2, 3, 4, 5}

# Use pop() in a loop until the set is empty
while sample_set:
    element = sample_set.pop()
    print("Popped Element:", element)
    print("Updated Set:", sample_set)        

Output

Popped Element: 1
Updated Set: {2, 3, 4, 5}
Popped Element: 2
Updated Set: {3, 4, 5}
Popped Element: 3
Updated Set: {4, 5}
Popped Element: 4
Updated Set: {5}
Popped Element: 5
Updated Set: set()

Example 3

Here this example shows how to handle the KeyError exception when trying to pop an element from an empty set.

# Define an empty set
empty_set = set()

# Try to pop an element from the empty set
try:
    empty_set.pop()
except KeyError as e:
    print("Error:", e)  

Output

Error: 'pop from an empty set'

Example 4

This example shows the use of the pop() method with a set containing different data types.

# Define a set with different data types
mixed_set = {1, "two", 3.0, (4, 5)}

# Pop an element
popped_element = mixed_set.pop()

# Print the popped element and the updated set
print("Popped Element:", popped_element)  
print("Updated Set:", mixed_set)          

Output

Popped Element: 1
Updated Set: {(4, 5), 3.0, 'two'}
python_set_methods.htm
Advertisements