Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed: KeyError caused due to the same element getting removed from a set twice #216

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

anmol-aidora
Copy link

for item_a in set_a:
    for item_b in set_b:
        if <some condition:True>:
            set_a.remove(item_a)

As you can see, if there are multiple items in set_b for which the condition evaluates to True, set_a.remove(item_a) will run twice, which will cause KeyError for second time onwards.

To solve this problem, I am checking whether the item_a is there in the set_a before removing. If it is, then remove, if it isn't then continue without removing as we have already removed it

… set twice

for item_a in set_a:
    for item_b in set_b:
        if <some condition:True>:
            set_a.remove(item_a)

As you can see, if there are multiple items in set_b for which the condition evaluates to True, set_a.remove(item_a) will run twice, which will cause KeyError for second time onwards.

To solve this problem, I am checking whether the item_a is there in the set_a before removing. If it is, then remove, if it isn't then continue without removing as we have already removed it
@stefan6419846
Copy link

There should probably be a test as well which covers this case. Additionally, using uncommon_items.discard(item_a) directly should do the same with less code.

@anmol-aidora
Copy link
Author

There should probably be a test as well which covers this case. Additionally, using uncommon_items.discard(item_a) directly should do the same with less code.

Thanks @stefan6419846 for pointing out this method. For the uninitiated:
The discard() method removes the specified item from the set. This method is different from the remove() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.

I am not sure how to write a test case for this. I will take that up later

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants