-4
a = True
print(('A','B')[a == False])

Could you please explain me in detail, preferably line-by-line what will be the output?

praj hegde
  • 15
  • 6
  • 2
    `False` is actually just an integer 0. `True` is just an integer 1. Does that answer your question? – Abdul Aziz Barkat Feb 20 '21 at 07:00
  • 3
    You'll learn better if you work it out by yourself, step by step. Figure out what the value of each part of the expression will be, then combine them. – Barmar Feb 20 '21 at 07:01
  • No. Instead, please explain exactly what you don't understand from the output you get when you trace this code. Doing that initial investigation is *your* task before you post here. Please go through the [intro tour](https://stackoverflow.com/tour), the [help center](https://stackoverflow.com/help) and [how to ask a good question](https://stackoverflow.com/help/how-to-ask) to see how this site works and to help you improve your current and future questions, which can help you get better answers. – Prune Feb 20 '21 at 07:02
  • Does this answer your question? [Logical indexing with lists](https://stackoverflow.com/questions/36721383/logical-indexing-with-lists) – Gino Mempin Feb 20 '21 at 07:04

2 Answers2

0
  1. a is set to True, and Python's bool is a subclass of the int type, so a can be interpreted as 1.

  2. (Omitting the print statement because that shouldn't need explaining), a tuple ("A", "B") whose indices are 0 and 1 respectively, is indexed at the result of the boolean expression a == False. The result of the expression is False since a is True, so a == False is False and therefore is interpreted as 0, so the tuple is indexed at index 0, which prints "A".

ddejohn
  • 8,775
  • 3
  • 17
  • 30
0

this code is confusing in part because it relies on dynamic type conversion. This is not particularly well written code.

a = True 
idx = (a == False) # False
("A", "B")[idx] # idx gets converted to int(False) -> 0
("A", "B")[0] # -> "A"

The tricky part is that False when cast as an int type is equal to 0, which is then used as an index for the tuple ("A", "B"). This is bad practice and generally confusing.

anon01
  • 10,618
  • 8
  • 35
  • 58