4

Condider the following example:

>>> {1, True}
set([True])
>>
>>> {True, 1}
set([1])

Why is the set represented differently, depending on the order of the elements?

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • 3
    Because booleans are a subclass of `int` and `True == 1` (and `False == 0`). This is a duplicate. – Martijn Pieters Dec 24 '13 at 09:24
  • Related: [Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?](http://stackoverflow.com/q/2764017) Hard to searh for the duplicate. – Martijn Pieters Dec 24 '13 at 09:35
  • @MartijnPieters One of the examples can be found [here](http://stackoverflow.com/questions/10419918/adding-the-number-1-to-a-set-has-no-effect/). – devnull Dec 24 '13 at 09:38

2 Answers2

4

This happens because 1 and True are equal to each other:

>>> True == 1
True
>>> 1 == True
True

The set retains one element from each equality class.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

bool is subclass of int class

>>> issubclass(bool, int)
True

>>> True+1
2
>>> True == 1
True
Vb407
  • 1,577
  • 2
  • 15
  • 27