Home > Net >  python: how to understand for Boolean expression: a and b not in list
python: how to understand for Boolean expression: a and b not in list

Time:07-09

def i(obj, x):
    if obj and x not in obj:
        return x
    else:
        return obj

print(i([], 6))
#prints []

def i(obj, x):
    if x and obj not in obj:
        return x
    else:
        return obj

print(i([], 6))
#prints 6

how do you formalize the logical expression here?
"obj" and "x" for both case are not in "obj", are they? if so, how to read correctly these two expressions. I thought they are the same:

if obj and x not in obj
if x and obj not in obj

CodePudding user response:

obj = []
x = 6

if obj and x not in obj
if x and obj not in obj

The first conditional. “if Obj” will evaluate to False as the List “obj” is empty. x not in obj will evaluate to true because x is not in the empty list. This line evaluates to false. As False AND True = False

The second line. “if x” will evaluate to true as integers greater than 0 evaluate to true. And “if obj not in obj” will evaluate to true as the obj’s are the same. Technically obj is not in obj. Obj IS THE SAME AS (==) to obj. This TRUE AND TRUE. Evaluates to True.

Difference is how lists vs integers get evaluated as booleans.

To answer your full question the first Boolean ends up with x being returned whereas the second Boolean ends up with obj getting returned.

  • Related