Python: Remove all elements from set using clear() or difference_update() or discard()

In this article we will discuss different ways to remove all elements from a set in python.

Remove all elements from a set using clear() function

In python, the Set class provides a function clear() that can empty a set i.e. delete all elements from the set. For example,

# Create a Set of numbers 
set_of_num = {1, 2, 11, 6, 7, 4, 5, 6} 

# Delete all elements in the set 
set_of_num.clear() 

print('Set Contents: ') 
print(set_of_num)

Output

Set Contents: 
set()

To confirm, if all elements are deleted from the set or not, we can check the size of the set. For example,
# Check the size of list to confirm if all elements are deleted
print('Set Size: ', len(set_of_num))

Output:
Set Size:  0

Remove all elements from a set using difference_update()

In python, the Set class provides a function difference_update() that accepts a sequence as an argument and deletes all the elements in this sequence from the set. Let’s use this to remove all elements of the set,

# Set of numbers
set_of_num = {1, 2, 11, 6, 7, 4, 5, 6}

# Delete all elements of a set from the same set | Empty a set
set_of_num.difference_update(set_of_num)

print('Set Contents: ')
print(set_of_num)

Output:
Set Contents: 
set()

We passed the same set object as an argument in the difference_update(), so it deleted all elements of the set.

Advertisements

To confirm, if all elements are deleted from the set or not, we can check the size of the set. For example,

# Check the size of list to confirm if all elements are deleted
print('Set Size: ', len(set_of_num))

Output:
Set Size:  0

Remove all elements from a set while iterating using for loop and discard()

If we iterate over a set and try to remove each element while iteration, then it will raise error,

# Set of numbers
set_of_num = {1, 2, 11, 6, 7, 4, 5, 6}

# RuntimeError: Set changed size during iteration
for elem in set_of_num:
    set_of_num.discard(elem)

Error
RuntimeError: Set changed size during iteration

It is because we can not modify a set while iterating over it.

So, we will create a list of the set elements, then iterate over that list and for each element, we will delete it from the set,

# Set of numbers
set_of_num = {1, 2, 11, 6, 7, 4, 5, 6}

# Iterate over the elements of set (by converting it to a list)
for elem in list(set_of_num):
    # Remove each element
    set_of_num.discard(elem)

print('Set Contents: ')
print(set_of_num)

Output:
Set Contents: 
set()

To confirm, if all elements are deleted from the set or not, we can check the size of the set. For example,
# Check the size of list to confirm if all elements are deleted
print('Set Size: ', len(set_of_num))

Output:
Set Size:  0

It seems to be an overkill for the small job of just clearing a set, but this solution can be useful if you want to delete some specific elements from the set, while iterating over the set.

The complete example is as follows,

def main():

    print('*** Remove all elements from a set using clear() function ***')

    # Set of numbers
    set_of_num = {1, 2, 11, 6, 7, 4, 5, 6}

    print('Set Contents: ')
    print(set_of_num)

    # Delete all elements in the set
    set_of_num.clear()

    print('Set Contents: ')
    print(set_of_num)

    # Check the size of list to confirm if all elements are deleted
    print('Set Size: ', len(set_of_num))

    print('*** Remove all elements from a set using difference_update() ***')

    # Set of numbers
    set_of_num = {1, 2, 11, 6, 7, 4, 5, 6}

    # Delete all elements of a set from the same set | Empty a set
    set_of_num.difference_update(set_of_num)

    print('Set Contents: ')
    print(set_of_num)

    # Check the size of list to confirm if all elements are deleted
    print('Set Size: ', len(set_of_num))

    print('*** Remove all elements from a set using for loop and discard() ***')

    # Set of numbers
    set_of_num = {1, 2, 11, 6, 7, 4, 5, 6}

    # RuntimeError: Set changed size during iteration
    '''
    for elem in set_of_num:
        set_of_num.discard(elem)
    '''

    # Iterate over the elements of set (by converting it to a list)
    for elem in list(set_of_num):
        # Remove each element
        set_of_num.discard(elem)

    print('Set Contents: ')
    print(set_of_num)

    # Check the size of list to confirm if all elements are deleted
    print('Set Size: ', len(set_of_num))


if __name__ == '__main__':
   main()

Output:
*** Remove all elements from a set using clear() function ***
Set Contents: 
{1, 2, 4, 5, 6, 7, 11}
Set Contents: 
set()
Set Size:  0
*** Remove all elements from a set using difference_update() ***
Set Contents: 
set()
Set Size:  0
*** Remove all elements from a set using for loop and discard() ***
Set Contents: 
set()
Set Size:  0

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top