Is there any explanation about the following Python condition syntax?
>>> a = 10
>>> s = (0, 1)[a<10]
>>> print s
0
>>> a = -10
>>> s = (0, 1)[a<10]
>>> print s
1
It seems to work like an if
statement. Why does this work?
In Python, bool
is a subclass of int
.
>>> issubclass(bool, int)
True
In other word, False
is equal to 0, and True
is equal to 1:
>>> False == 0
True
>>> True == 1
True
So they can be used as a index:
>>> ['No', 'Yes'][False] # ['No', 'Yes'][0]
'No'
>>> ['No', 'Yes'][True] # ['No', 'Yes'][1]
'Yes'
The expression a < 10
yields True
or False
based on the value of a
. So (0, 1)[a < 10]
will yield 0
or 1
accordingly.
(0, 1)
is a 2-element tuple. You can access its values using the index accessors [0]
and [1]
like this:
>>> (0, 1)[0]
0
>>> (0, 1)[1]
1
Now, in Python, the boolean values True
and False
are actually instances of int
(because bool
is a subtype of int
):
>>> issubclass(bool, int)
True
>>> isinstance(True, int)
True
>>> isinstance(False, int)
True
The int values of True
and False
are 1
and 0
:
>>> True == 1
True
>>> False == 0
True
So you can actually use them two access the elements in your 2-element tuple:
>>> (0, 1)[False]
0
>>> (0, 1)[True]
1
And that explains why specifying a condition there—which returns a boolean—will work as well.
This is also mentioned in the documentation (emphasis mine):
Boolean values are the two constant objects
False
andTrue
. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively.
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