Python | Remove items from a set

Python Methods and Functions

Examples:

 Input: set ([12, 10, 13, 15, 8, 9]) Output: {9, 10, 12, 13, 15} {10, 12, 13, 15} {12, 13, 15} {13, 15} {15} set () Input: set (['a',' b', 'c',' d', 'e']) Output: {' d', 'c',' a', 'b'} {' c', 'a',' b'} {'a',' b'} {'b'} set () 

Using the pop () method
Pop () — it is a built-in method in Python that is used to retrieve or remove items one by one from a set. The element that is the smallest in the set is first removed and then removed in ascending order. In the following program, the while loop continues to remove elements one by one until the set is empty.

# Python program to remove items from a set
# Using the pop () method

def Remove ( initial_set):

while initial_set:

initial_set.pop ()

print (initial_set)

 
Driver code

initial_set = set ([ 12 , 10 , 13 , 15 , 8 , 9 ])

Remove (initial_set)

Output:

 {9, 10, 12, 13, 15} {10, 12, 13, 15} {12, 13, 15} {13, 15} {15} set () 




Tutorials