Excerpt from my JavaScript console:
> 0 in [1, 2]
true
Why?
Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true. To make life easier, C Programmers typically define the terms "true" and "false" to have values 1 and 0 respectively.
When converting to bool, the following values are considered false : the boolean false itself. the integer 0 (zero) the floats 0.0 and -0.0 (zero)
Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true.
Treating integers as boolean values Whenever an integer value is tested to see whether it is true of false, 0 is considered to be false and all other integers are considered be true.
Because "in" returns true if the specified property/index is available in the object. [1, 2] is an array, and has a object at the 0 index. Hence, 0 in [1, 2], and 1 in [1, 2]. But !(2 in [1, 2]).
Edit: For what you probably intended, David Dorward's comment below is very useful. If you (somewhat perversely) want to stick with 'in', you could use an object literal
x = {1: true, 2: true};
This should allow 1 in x && 2 in x && !(0 in x)
etc. But really, just use indexOf.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With