How to discard multiple elements from a set?

Question:

I am trying to discard elements with length less than 10, but it doesn’t work.

a = {'ab', 'z x c v b n m k l j h g f f d s a a', 'q w e r t y u i o p'}
a.discard(x for x in a if len(x.split())<9) # discard elements with length<10
print(a)

I got this output:

{'z x c v b n m k l j h g f f d s a a', 'q w e r t y u i o p', 'ab'}

'ab' doesn’t match the condition, I don’t know why it’s still here?

And my desired output is:

{'z x c v b n m k l j h g f f d s a a', 'q w e r t y u i o p'}

Asked By: Hello World

||

Answers:

You need to call discard on individual items, not on the generator of items to be discarded:

for x in [x for x in a if len(x.split()) < 9]:
    a.discard(x)

Be mindful that you can’t discard items while iterating through the set, so this will not work:

for x in a:
    if len(x.split()) < 9:
        a.discard(x)

Although this is beyond your question, I’d like to add that there are better ways to do what you want through set comprehension or set subtraction as suggested in another answer and comments.

Answered By: Alex Bochkarev

You are using the wrong method to remove elements from the set. discard removes an element from the set only if it exists. You want to remove elements based on a condition, so you need to use a different approach. Here’s a corrected version of the code:

a = {'ab', 'z x c v b n m k l j h g f f d s a a', 'q w e r t y u i o p'}
a = {x for x in a if len(x.split()) >= 9}
print(a)

This code creates a new set with only the elements that meet the condition, and then assigns it back to a. The desired output is achieved:

{'z x c v b n m k l j h g f f d s a a', 'q w e r t y u i o p'}
Answered By: mhrsalehi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.