The Python set pop method is one of the set method used to remove a random from a set. It is because the Python set won’t store the items using indexes. You can assign that removed item to a new variable for further reference.
The syntax of this Python set pop method is
set.pop()
Python set pop example
In this example, we declared a numeric set. Next, we used this set pop function to remove a random set item from the existing set.
# Python set pop numeric_set = {150, 250, 350, 450, 550} print('The Original Set : ', numeric_set ) numeric_set.pop() print('The Set after pop: ', numeric_set)
OUTPUT
This set pop code is the same as the above example. However, this time we are assigning the removed set value to a new variable and printing the same.
TIP: Please refer to the Python set to understand Sets in Python.
numeric_set = {150, 250, 350, 450, 550} print('The Original Set : ', numeric_set ) x = numeric_set.pop() print('\npop Item : ', x) print('The Set after pop: ', numeric_set)
OUTPUT
Python pop example 2
In this example, we are using the set pop method to remove all the existing set items one after the other.
numeric_set = {15, 25, 35, 45, 55} print('The Original Set : ', numeric_set ) x = numeric_set.pop() print('\npop Item : ', x) print('The Set after pop: ', numeric_set) y = numeric_set.pop() print('\npop Item : ', y) print('The Set after pop: ', numeric_set) z = numeric_set.pop() print('\npop Item : ', z) print('The Set after pop: ', numeric_set) zz = numeric_set.pop() print('\npop Item : ', zz) print('The Set after pop: ', numeric_set)
OUTPUT
This time, we are working with Python pop function on the string set.
fruits_set = {'Mango', 'Cherry', 'Apple', 'Kiwi'} print('The Original Set : ', fruits_set) x = fruits_set.pop() print('pop Item : ', x) print('The Set after pop: ', fruits_set) y = fruits_set.pop() print('\npop Item : ', y) print('The Set after pop: ', fruits_set)
OUTPUT
Here, we declared a mixed set. Next, we used the set pop method to remove a random item from a set.
mixed_set = {'Mango', 10, 'Cherry', 20, 'Apple', 30, 'Kiwi'} print('The Original Set : ', mixed_set) x = mixed_set.pop() print('\npop Item : ', x) print('The Set after pop: ', mixed_set) y = mixed_set.pop() print('\npop Item : ', y) print('The Set after pop: ', mixed_set)
OUTPUT