python - Adding 1 to a set containing True does not work -
i have started learn python , have encountered little strange when playing sets. following code sample doesn't produce expected results.
a_set = {true,2,3,4} a_set.add(1)
i expected a_set have values {true, 1, 2, 3, 4}
instead code produced {true, 2, 3, 4}
.
trying variations on produced same results:
a_set = {1,2,3,4} a_set.add(true)
expected {true, 1, 2, 3, 4}
actual {1, 2, 3, 4}
trying false
, 0
obtained same results:
a_set = {false,2,3,4} a_set.add(0)
expected {false, 0, 2, 3, 4}
actual {false, 2, 3, 4}
a_set = {0,2,3,4} a_set.add(false)
expected {false, 0, 2, 3, 4}
actual {0, 2, 3, 4}
i understand bool
type inherited int
, true == 1
, false == 0
still little surprised above results.
does know if behaviour design? possible have set contains both true
, false
, 0
, , 1
?
i did perform quite bit of googling not able find answer questions.
thanks in advance
update
in response comments below agree following question partially answers question.
is false == 0 , true == 1 in python implementation detail or guaranteed language?
but feel doesn't answer query have regarding behaviour of sets , whether possible have set containing both true
, 1
. though bool
inherited int
, different types, found fact set cannot distinguish between true
, 1
little confusing. question behaviour of sets in python not true == 1
.
for historical (hysterical?) reasons python's bool
type subclass of int
, , true
equal 1 , false
equal 0.
they hash same location well:
>>> true == 1 true >>> hash(true) == hash(1) true >>> false == 0 true >>> hash(false) == hash(0) true
since both true
, 1
considered equal , hash same slot, both set
, dict
treat them same thing.
you'll see same dictionary:
>>> true in {1: 'foo'} true >>> 1 in {true: 'foo'} true
this behaviour extends other numbers too; floating point values equal integer values show same behaviour:
>>> {1.0, 1, 2.0, 2} {1, 2}
but @ least reasons why happens little more.. obvious.
Comments
Post a Comment