What does syntax like 'FT'[boolean] in Python?

Viewed 65

First of all, I'm very sorry that I ask about a fairly basic problem.
When I studying syntactic sugar in Python, I found a very interesting syntax like below:

#'FT'[boolean]
print('FT'[False]) # F
print('FT'[True])  # T
print('NY'[False]) # N
print('NY'[True])  # Y

As a combination of 'String' and [square brackets],
If a False boolean value is entered in [square brackets],
the first character of 'String' is returned, and vice versa, the second character of 'String' is returned.

What is the name of this syntax and when did it appear and what is the principle of it?

1 Answers

It's normal indexing. What may be confusing you is the fact that bool is a subclass of int (with True == 1 and False == 0) which means that

'FT'[False]

is equivalent to

'FT'[0]

which is, of course, 'F'.

(You might also not be familiar with indexing a str literal directly, as opposed to a str-valued variable: print('FT'[False]) is the same as

x = 'FT'
print(x[False])

)

Related