Open In App

Python | Remove items from Set

Last Updated : 01 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 characteristics of a 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()

Set in Python

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.

Methods of removing items from the set

Remove Elements from 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. 

Python3




def Remove(initial_set):
    while initial_set:
        initial_set.pop()
        print(initial_set)
 
 
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()

Remove items from Set using discard() Method

Initialize a set my_set with the given elements. Enter a loop that runs as long as there are elements in the set my_set. Find the maximum element in the set using the max() function and remove it from the set using the discard() method. Print the updated set after each removal. Exit the loop when the set my_set becomes empty.

Python3




my_set = set([12, 10, 13, 15, 8, 9])
 
 
while my_set:
    my_set.discard(max(my_set))
    print(my_set)


Output

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

The time complexity of the given code is O(n^2), where n is the size of the input set. This is because for each element in the set, the max() function is called, which has a time complexity of O(n). Since there are n elements in the set, the total time complexity becomes O(n^2).

The space complexity of the given code is O(n), where n is the size of the input set. This is because a set of size n is initialized in memory, and the loop runs until all the elements are removed from the set. Therefore, the maximum amount of memory used by the program is proportional to the size of the input set.

Delete Elements from Set Using remove() Method

Initialize set. Use for loop to iterate length of set times. Use the remove method on the first element of the set which is retrieved by the next() method on iter() function. 

Python3




my_set = set([12, 10, 13, 15, 8, 9])
 
for i in range(len(my_set)):
    my_set.remove(next(iter(my_set)))
    print(my_set)
     
    


Output

set([9, 10, 12, 13, 15])
set([10, 12, 13, 15])
set([12, 13, 15])
set([13, 15])
set([15])
set([])


Time complexity: O(N) Here N is the length of the set and we are iterating over length of the set. 
Space complexity:  O(N) N is set lenght. 



Previous Article
Next Article

Similar Reads

Python Program to find the profit or loss when CP of N items is equal to SP of M items
Given [Tex]N   [/Tex]and [Tex]M   [/Tex]denoting that the Cost Price of N articles is equal to the Selling Price of M articles. The task is to determine the profit or Loss percentage. Examples:  Input: N = 8, M = 9 Output: Loss = -11.11% Input: N = 8, M = 5 Output: Profit = 60% Formula:-  Below is the implementation of the above approach: C/C++ Cod
1 min read
Python - Remove K value items from dictionary nesting
Given dictionary with multiple nestings, remove all the keys with value K. Input : [{"Gfg" : {"a" : 5, "b" : 8, "c" : 9}}, {"is" : {"j" : 8, "k" : 10}}, {"Best" : {"i" : 16}}], K = 8 Output : [{'a': 5}, {'c': 9}, {'k': 10}, {'i': 16}] Explanation : All the keys with value 8, ("b", "j") has been removed. Input : [{"Gfg" : {"a" : 5, "b" : 8, "c" : 9}
4 min read
How to remove all items in a Qlistwidget in PyQt5?
Prerequisite: PyQt5QListWidget There are so many options provided by Python to develop GUI applications and PyQt5 is one of them. PyQt5 is a cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. In this articl
2 min read
How to remove multiple selected items in listbox in Tkinter?
Prerequisite: Tkinter, Listbox in Tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In t
2 min read
Python | Common items among dictionaries
Sometimes, while working with Python, we can come across a problem in which we need to check for the equal items count among two dictionaries. This has an application in cases of web development and other domains as well. Let's discuss certain ways in which this task can be performed. Method #1 : Using dictionary comprehension This particular task
6 min read
Python | Convert an array to an ordinary list with the same items
When working with arrays, a frequent requirement is to convert them into standard lists, while retaining the original elements. This article delves into the art of effortlessly transforming arrays into lists using Python, maintaining the integrity of their contents. Input: array('i', [1, 3, 5, 3, 7, 1, 9, 3])Output: [1, 3, 5, 3, 7, 1, 9, 3]Explanat
4 min read
Python Dictionary items() method
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key : value pair.In Python Dictionary, items() method is used to return the list with all dictionary keys with values. Syntax: dictionary.items()Parameters: T
2 min read
Python program to find the sum of all items in a dictionary
Given a dictionary in Python, write a Python program to find the sum of all items in the dictionary. Examples: Input : {'a': 100, 'b':200, 'c':300}Output : 600 Input : {'x': 25, 'y':18, 'z':45}Output : 88 Method #1: Using Inbuilt sum() Function Use the sum function to find the sum of dictionary values. C/C++ Code # Python3 Program to find sum of #
6 min read
Python | Delete items from dictionary while iterating
A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple. Note: In Python 2 dictionary keys were unordered. As of Python 3, they
3 min read
Python | Insert the string at the beginning of all items in a list
Given a list, write a Python program to insert some string at the beginning of all items in that list. Examples: Input : list = [1, 2, 3, 4], str = 'Geek' Output : list = ['Geek1', 'Geek2', 'Geek3', 'Geek4']Input : list = ['A', 'B', 'C'], str = 'Team' Output : list = ['TeamA', 'TeamB', 'TeamC'] There are multiple ways to insert the string at the be
3 min read
Article Tags :
Practice Tags :