-4

['f', 't'][bool('spam')]

this gives result ,

't'

But I cannot understand how this sample of code works?

Promila Ghosh
  • 389
  • 4
  • 12
nppn
  • 3
  • 4
  • https://stackoverflow.com/questions/21732123/convert-true-false-value-read-from-file-to-boolean and https://stackoverflow.com/questions/20840803/how-to-convert-false-to-0-and-true-to-1 – Martheen Jun 20 '22 at 07:26

1 Answers1

-1

Any non-empty string is evaluated to True in a boolean context, so we have

['f', 't'][True]

The bool type is a subtype of int, with True and False basically being 1 and 0 respectively, so we end up with

['f', 't'][1]

Which should make it clear why the output is 't'.

Similarly,

['f', 't'][bool('spam')]

will output 'f'.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154