koodingu
koodingu

Reputation: 41

How does this print syntax work? print('something', ['a', 'list'][boolean])

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.

Upvotes: 2

Views: 68

Answers (3)

BoarGules
BoarGules

Reputation: 16951

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

Upvotes: 1

modesitt
modesitt

Reputation: 7210

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

Upvotes: 4

DeepSpace
DeepSpace

Reputation: 81664

  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

Upvotes: 4

Related Questions