We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

Python Set: Remove single or multiple elements from a set?

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

Remove a single element from a set

Suppose we have a set of numbers in python,

Advertisements

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

print('Original Set: ')
print(set_of_num)

Output:

Original Set: 
{1, 2, 4, 5, 6, 7, 11}

Now we want to remove an element from this set. There are different ways to do this. Let’s discuss them one by one,

Use set.remove() to delete an element from a set by value

In Python, the Set class provides a function remove(), it accepts an element as an argument and if that element exists in the set, then it deletes that. Whereas, if that element does not exist in the set, then it raises a KeyError. We are going to use this remove() function to delete an element from set,

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

print('Original Set: ')
print(set_of_num)

# Remove an element with value 11 from the set
set_of_num.remove(11)

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

Output:

Original Set: 
{1, 2, 4, 5, 6, 7, 11}
Set Contents After Deletion:
{1, 2, 4, 5, 6, 7}

We deleted the element with value 11 from the set.

What if we call remove() to delete an element that does not exist in the set?

Try to remove an element that does not exist in the Set

If we call the remove() function to delete an element that does not exist in the set, then it will raise KeyError. For example,

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

# Error
set_of_num.remove(20)

Error

KeyError: 20

We tried to remove an element with value 20 from the set using remove() function, but as 20 did not exist in the set, therefore it raised the KeyError. Now to avoid the KeyError, we should always first check if an element exists in the set or not before trying to delete that element. For example,

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

# element to be deleted
value = 20

if value in set_of_num:
    set_of_num.remove(value)
else:
    print('Element does not exist in set')

Output:

Element does not exist in set

or we wan also use try / except to avoid this kind of KeyError,

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

# element to be deleted
value = 20

try:
    set_of_num.remove(value)
except KeyError:
    print('Can not delete en element, which is not present in set')

Output:

Can not delete en element, which is not present in set

Remove an element from a set using discard()

In python, the Set class provides another function to remove an element from the set i.e. discard(). It accepts an element as an argument and if that element exists in the set, then it deletes that. Whereas, if a set does not contain that element, then discard() function does not do anything. It means unlike remove() function,  discard() will not raise any error, in case element does not exist in the Set.

Let’s use discard() function to remove an element with value 4 from the set,

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

# Remove an element from the set
set_of_num.discard(4)

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

Output:

Set Contents:
{1, 2, 5, 6, 7, 11}

Now let’s try to remove an element that does not exist in the set,

# Delete element which is not present in the set
set_of_num.discard(20)

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

Output:

Set Contents:
{1, 2, 5, 6, 7, 11}

An element with value 20 does not exist in the set, but discard() function did nothing.

Removing multiple elements from a set

Suppose we have a set and we want to delete 4 elements from this i.e.

Set of numbers,

{1, 2, 11, 6, 7, 4, 5, 6}

Elements to be deleted,

[1, 2, 4, 5]

Final Set should be,

{6, 7, 11}

There are various ways to do this. Let’s discuss them one by one,

Removing multiple 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 delete all elements of the list from the set,

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

# Elements to be deleted
to_delete = [1, 2, 4, 5]

# Remove all elements of list from the set
set_of_num.difference_update(to_delete)

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

Output:

Modified Set Contents:
{6, 7, 11}

So, we deleted 4 elements from the set in a single line.

Removing multiple elements from a set using for loop & discard()

Another way to delete multiple elements from a set is by iterating over the elements to be deleted and deleting them one by one from the set. For example,

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

# Elements to be deleted
to_delete = [1, 2, 4, 5]

# Iterate over the list of elements (to be deleted)
for elem in to_delete:
    # Remove element from the set
    set_of_num.discard(elem)

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

Output:

Modified Set Contents:
{6, 7, 11}

Removing multiple elements from a set while iterating over it

Suppose we want to iterate over a set of numbers and delete elements which are less than 6 while iterating. Let’s see how to do that,

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

# Iterate over elements in set and remove elements while iterating
for elem in list(set_of_num):
    if elem < 6:
        set_of_num.discard(elem)


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

Output:

Modified Set Contents:
{6, 7, 11}

As we can not modify a set while iterating over it, so we created a list of set elements and then iterated over that list. While iterating over that list elements, we deleted each element from the set if it was less than 6.

Removing multiple elements from a set that satisfies a given condition

Suppose we want to delete elements from a set that satisfy a given condition. For that we have created a function,

def delete_from_set_if(main_set, condition):
    for elem in list(main_set):
        if condition(elem):
            main_set.discard(elem)

It accepts a set and a function as arguments, then deletes the elements from the set for which the function returns True.

Let’s use this to delete elements which are greater than 2 but less than 6 from the set,

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

delete_from_set_if(set_of_num, lambda x : x<6 and x > 2)

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

Output:

Modified Set Contents:
{1, 2, 6, 7, 11}

The complete example is as follows,

def delete_from_set_if(main_set, condition):
    for elem in list(main_set):
        if condition(elem):
            main_set.discard(elem)

def main():

    print('*** Remove an element from a set using remove() ***')

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

    print('Original Set: ')
    print(set_of_num)

    # Remove an element with value 11 from the set
    set_of_num.remove(11)

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

    print('Try to remove an element that does not exist in the set ')

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

    # Error
    #set_of_num.remove(20)

    print('Python set remove if exist using remove() function')

    # element to be deleted
    value = 20

    if value in set_of_num:
        set_of_num.remove(value)
    else:
        print('Element does not exist in set')

    print('Python set remove if exist using try / except')

    # element to be deleted
    value = 20

    try:
        set_of_num.remove(value)
    except KeyError:
        print('Can not delete en element, which is not present in set')

    print('*** Remove an element from a set using discard() ***')

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

    # Remove an element from the set
    set_of_num.discard(4)

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

    print('Try to remove ane element that is not present in the set ')

    # Delete element which is not present in the set
    set_of_num.discard(20)

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

    print('**** Removing multiple elements from a set ****')

    print('*** Removing multiple elements from a set using difference_update() ***')

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

    # Elements to be deleted
    to_delete = [1, 2, 4, 5]

    # Remove all elements of list from the set
    set_of_num.difference_update(to_delete)

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

    print('*** Removing multiple elements from a set using for loop & discard() ***')

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

    # Elements to be deleted
    to_delete = [1, 2, 4, 5]

    # Iterate over the list of elements (to be deleted)
    for elem in to_delete:
        # Remove element from the set
        set_of_num.discard(elem)

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

    print('*** Removing multiple elements from a set while iterating over it***')

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

    # Iterate over elements in set and remove elements while iterating
    for elem in list(set_of_num):
        if elem < 6:
            set_of_num.discard(elem)


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

    print('*** Removing multiple elements from a set that satisfies a given condition***')

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

    delete_from_set_if(set_of_num, lambda x : x<6 and x > 2)

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


if __name__ == '__main__':
   main()

Output:

*** Remove an element from a set using remove() ***
Original Set: 
{1, 2, 4, 5, 6, 7, 11}
Set Contents After Deletion:
{1, 2, 4, 5, 6, 7}
Try to remove an element that does not exist in the set 
Python set remove if exist using remove() function
Element does not exist in set
Python set remove if exist using try / except
Can not delete en element, which is not present in set
*** Remove an element from a set using discard() ***
Set Contents:
{1, 2, 5, 6, 7, 11}
Try to remove ane element that is not present in the set 
Set Contents:
{1, 2, 5, 6, 7, 11}
**** Removing multiple elements from a set ****
*** Removing multiple elements from a set using difference_update() ***
Modified Set Contents:
{6, 7, 11}
*** Removing multiple elements from a set using for loop & discard() ***
Modified Set Contents:
{6, 7, 11}
*** Removing multiple elements from a set while iterating over it***
Modified Set Contents:
{6, 7, 11}
*** Removing multiple elements from a set that satisfies a given condition***
Modified Set Contents:
{1, 2, 6, 7, 11}

Cart

Your Cart is Empty

Back To Shop