2
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.

rdas
  • 20,604
  • 6
  • 33
  • 46
koodingu
  • 41
  • 4

3 Answers3

4

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

modesitt
  • 7,052
  • 2
  • 34
  • 64
  • 1
    `[-5 - 256]` to be precise – DeepSpace Apr 28 '19 at 17:42
  • 1
    Whether or not *any* integers are pre-allocated is an implementation detail that should not be counted on. Neither `True is 1` nor `False is 0` is guaranteed by the language, though `True == 1` and `False == 0` are. – chepner Apr 28 '19 at 17:55
  • 1
    @chepner For sake of completeness I think we don't even need to trust `True == 1` (and `False == 0`) for "boolean indexing" to work. Only `int(True) == 1` and `int(False) == 0` must stay true – DeepSpace Apr 28 '19 at 17:59
  • 1
    `True == 1` can be guaranteed even if `bool` isn't a subclass of `int`; c.f. `1 == 1.0`. – chepner Apr 28 '19 at 18:04
  • 1
    In Python 2, `True` isn't a keyword, so something like `True = 1` can make `True is 1` true. Python 3 closed that loophole, though :) – chepner Apr 28 '19 at 18:08
4
  1. Python's bool is a subclass of int, where True is 1 and False is 0.
    isinstance(True, int) # True
  2. As such, booleans can be used as indexes. ['a', 'list'][boolean] evaluates to
    ['a', 'list'][0] if boolean is False or to ['a', 'list'][1] if boolean is True

This can be abused by using conditions directly:

x = 1
print(['no', 'yes'][x > 0])
# yes
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
1

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].

BoarGules
  • 16,440
  • 2
  • 27
  • 44