print('something', ['a', 'list'][boolean])
Depending on the boolean value this either prints, a or list.
I have never seen this notation before and am wondering how it works.
print('something', ['a', 'list'][boolean])
Depending on the boolean value this either prints, a or list.
I have never seen this notation before and am wondering how it works.
Notice the following in python
>>> True == 1
True
>>> False == 0
True
as booleans are integers (in Python). so [0,1,2][False] == 0 and [0,1,2][True] == 1
bool is a subclass of int, where True is 1 and False is 0. isinstance(True, int) # True['a', 'list'][boolean] evaluates to ['a', 'list'][0] if boolean is False or to ['a', 'list'][1] if boolean is TrueThis can be abused by using conditions directly:
x = 1
print(['no', 'yes'][x > 0])
# yes
The boolean is either True or False. If you have a list mylist then mylist[0] gets you the first element and mylist[1] gets you the second element. mylist[False] means the same as mylist[0]. Now suppose mylist contains ["list", "a"]. Then ["list", "a"][False] will give you the same value as mylist[0] which is "list".
You are accustomed to seeing index notation (for example [0]) after the name of a list, as in mylist[0]. But it can just as well be used after a list literal, as in ["list", "a"][0].