Special condition syntax with parentheses and brackets

Are there any explanations regarding the following syntax for Python conditions?

>>> 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 . Why does it work?

+4
source share
2 answers

In Python, bool is a subclass of int .

 >>> issubclass(bool, int) True 

In other words, False is 0, and True is 1:

 >>> False == 0 True >>> True == 1 True 

Therefore, they can be used as an index:

 >>> ['No', 'Yes'][False] # ['No', 'Yes'][0] 'No' >>> ['No', 'Yes'][True] # ['No', 'Yes'][1] 'Yes' 

The expression a < 10 gives True or False based on the value of a . Thus, (0, 1)[a < 10] will give 0 or 1 respectively.

+7
source

(0, 1) is a 2-element tuple . You can access your values ​​using the indexes for access [0] and [1] as follows:

 >>> (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 True and False values ​​are 1 and 0 :

 >>> True == 1 True >>> False == 0 True 

So, you can use their two element accesses in your 2-element tuple:

 >>> (0, 1)[False] 0 >>> (0, 1)[True] 1 

And this explains why a condition is returned here that returns a logical-work.

This is also mentioned in the documentation (my attention):

Booleans are two constant objects False and True . They are used to represent truth values ​​(although other values ​​may also be considered false or true). In numerical contexts (for example, when used as an argument to an arithmetic operator), they behave as integers 0 and 1, respectively.

+5
source

All Articles