Python | Remove items from Set
In this article, we will try to a way in which the elements can be removed from the set in a sequential manner. Before going into that let’s learn various characteristic of a set. A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. Python’s set class represents the mathematical notion of a set. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.
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
The pop() is an inbuilt method in Python that is used to pop out or remove the elements one by one from the set. The element that is the smallest in the set is removed first followed by removing elements in increasing order. In the following program, the while loop goes onto removing the elements one by one, until the set is empty.
# Python program to remove elements from 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()
Recommended Posts:
- Python | Get first K items in dictionary
- Python Dictionary | items() method
- Python | Pandas Series.items()
- Dictionary Methods in Python | Set 1 (cmp(), len(), items()...)
- Python | Common items among dictionaries
- Python | Delete items from dictionary while iterating
- Python | Sort the items alphabetically from given dictionary
- Python | Get items in sorted order from given dictionary
- Python program to find the sum of all items in a dictionary
- Python | Associating a single value with all list items
- Python | Type conversion of dictionary items
- Python | Insert the string at the beginning of all items in a list
- Python | Count number of items in a dictionary value that is a list
- Python | Convert an array to an ordinary list with the same items
- Python list remove()
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



