Home > Enterprise >  Cannot understand how following sample code works
Cannot understand how following sample code works

Time:06-20

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

this gives result ,

't'

But I cannot understand how this sample of code works?

CodePudding user response:

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

CodePudding user response:

If you try to convert a bool to int, you will find that False is 0 and True is 1

print(int(False))  # 0
print(int(True))  # 1

print(['f', 't'][1])  # "t"

Let's look at the implementation of bool

class bool(int):
    """
    bool(x) -> bool
    
    Returns True when the argument x is true, False otherwise.
    The builtins True and False are the only two instances of the class bool.
    The class bool is a subclass of the class int, and cannot be subclassed.
    """
  • Related