Python sets interpolation 1 and True

In the IPython 3 interactive shell:

In [53]: set2 = {1, 2, True, "hello"} In [54]: len(set2) Out[54]: 3 In [55]: set2 Out[55]: {'hello', True, 2} 

Is this because 1 and True get the same interpretation, so given that the set eliminates duplicates, only one of them remains (True)? How can we save both?

+7
python set
source share
1 answer

The set is a set of hashables . Although the 1 is True statement is False, the statement 1 == True is True. Because of this, they have the same hash value and cannot exist separately in the set, and you cannot keep them in the set

EDIT To make this explicit, as jme noted, this is because BOTHs are true - they are equal (for __eq__ ) and they have the same hash value (for __hash__ ).

In an ideal world, equal objects will also have the same hash value, and, fortunately, this is true for built-in types.

+7
source share

All Articles