c= {1,3,5,89.07, True, "Night", 1,3}
print(c)
when I run this code, the output I received was, {1, 3, 'Night', 5, 89.07}
but when I replaced the "True" bool with False, the output was, {False,1, 3, 'Night', 5, 89.07}
So, why it is not giving "True" bool in first case ?
CodePudding user response:
Note that a similar effect is observed for 0
:
>>> print({ 1, True })
{1}
>>> print({ 0, False })
{0}
This seems to be because in Python bool
is a subclass of int
, and often False
acts like 0
and True
like 1
:
>>> isinstance(True, int)
True
>>> False True
1
>>> False * 100
0
>>> 8 ** False
1
It's even the case that False == 0
and True == 1
!
So in your case because 1
is already in your set, adding True
to it makes no difference. But if you add False
you get a new element.
CodePudding user response:
It is because sets return UNIQUE values only. In python, True corresponds to 1 and False to 0. Therefore:
c = {0,False}
print(c)
# {0}
c = {1, False}
print(c)
#{False, 1}
c = {0, True}
print(c)
#{0, True}