Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why set.discard doesn't throw an error when a set is passed to it in Python?

My question is quite simple.

When I run

someSet = {1,2,3,4}
someSet.discard([5])

It gives the error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Traceback (most recent call last):
  File "File.py", line 2, in <module>
    someSet.discard([5])
TypeError: unhashable type: 'list'

Just like list, sets are also unhashable and can’t be stored in a set.
So, I expect the following code to generate an error:

someSet = {1,2,3,4}
someSet.discard({5})

But to my surprise, it did not generate any error. Why is it so? Does this mean that I am getting an error for list as there something other than it being unhashable which gives rise to the error? If yes, then what is that thing?

>Solution :

There’s a weird special case where if you pass another set to set.remove, set.discard, or x in set, the set is silently converted to a frozenset.

Note, the elem argument to the __contains__(), remove(), and discard() methods may be a set. To support searching for an equivalent frozenset, a temporary one is created from elem.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading