Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 421
koodingu Avatar asked May 31 '26 13:05

koodingu


1 Answers

  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
like image 113
DeepSpace Avatar answered Jun 02 '26 03:06

DeepSpace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!