Reputation: 101
In ver. 3.9.5:
>>> s1 = {True,1,1,2}
>>> s1
{True, 2}
>>> s2 = {1,1,True,2}
>>> s2
{1, 2}
gives an impression that all subsequent 1s after True are dropped and all Trues after1 are also dropped, while set object is being constructed. But other Truthy values but not 1 are not ignored in either of the cases.
>>> s3 = {False,0,""}
>>> s3
{False, ''}
>>> s3 = {False,(),0,""}
>>> s3
{False, '', ()}
>>> s4 = {0,False,(),0,""}
>>> s4
{0, '', ()}
Mutatis Mutandis for False and zero.
I couldn't find in python documentation for 3.9.5 about this logic explicitly. But I could see some literature about the dictionary implementation without keys being used for creating a set and optimization requirement. I have also had a glimpse of set object implementation atset object implementation which is beyond the scope of beginners and my salute to those 49 contributors and Mr.Ramond Hettinger. Simply put, I understand that the underlying logic uses hashing function to distinguish different values. Therefor I have to use
>>> hash(True)
1
>>> hash(3)
3
>>> hash(0)
0
>>> hash(False)
0
>>> hash(())
5740354900026072187
to explain to the beginners why the set object construction happens that way. But
>>> hash("")
0
despite that it gets included in s4 example above. Therefore I need further logic.
Now to the question. Is there any python documentation or article explaining the way unique elements are determined when set object is being constructed, for the benefit of Python beginners. My search in various tutorials have been in vain. Am I missing something which is pretty obvious?
Thanks for your time.
Upvotes: 2
Views: 51
Reputation: 8045
The reason why this happens - oddly enough, but normal in the context of programming languages - is because Python's booleans are actually subtypes of integers (0
and 1
to be specific).
isinstance(False, int) # >>> True
isinstance(True, int) # >>> True
Which is the reason for the set removing one or the other (dependent on order).
>>> {1, True}
{1}
>>> {True, 1}
{True}
>>> {0, False}
{0}
>>> {False, 0}
{False}
>>> {True, False}
{False, True} # Note the order change here as well.
>>> {0, 1}
{0, 1}
Note under Built-in Types - Numeric Types:
There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers.
Upvotes: 1