if v in word_dict == True
is evluated as if v in word_dict and word_dict==True
. This is called operator chaining.
Check this byte-code using dis module.
import dis
a={'a':1,'b':2,'c':3}
In [53]: dis.dis('"a" in a == True')
1 0 LOAD_CONST 0 ('a')
2 LOAD_NAME 0 (a)
4 DUP_TOP
6 ROT_THREE
8 COMPARE_OP 6 (in)
10 JUMP_IF_FALSE_OR_POP 18
12 LOAD_CONST 1 (True)
14 COMPARE_OP 2 (==)
16 RETURN_VALUE
>> 18 ROT_TWO
20 POP_TOP
22 RETURN_VALUE
In [54]: dis.dis('"a" in a and a==True')
1 0 LOAD_CONST 0 ('a')
2 LOAD_NAME 0 (a)
4 COMPARE_OP 6 (in)
6 JUMP_IF_FALSE_OR_POP 14
8 LOAD_NAME 0 (a)
10 LOAD_CONST 1 (True)
12 COMPARE_OP 2 (==)
>> 14 RETURN_VALUE
Both are evaluated in the same way. And in your case word_dict==True
is always False
as word_dict
is a dictionary. So, it would never enter the if
block and else
block is executed.
if some_bool_expr == True
and can be written as if some_bool_expr
and if some_bool_expr==False
can be written as if not some_bool_expr
.
Byte-code Instructions documentation link
LOAD_CONST
and LOAD_NAME
: push value onto the stack. After line 2 top of the stack is a
(not 'a'
)
DUP_TOP
: Duplicates the reference on top of the stack and pushes onto the stack. Now top of the stack is a
.
ROT_THREE
: Lifts second and third stack item one position up moves top down to position three. Now TOS
(top of the stack) is third element (a
) and 2nd element (a
) is now TOS
, 3rd element 'a'
is now 2nd element.
COMPARE_OP
: Tells the interpreter to pop the two topmost stack elements and perform an membership test(in
) between them, pushing the Boolean result back onto the stack. 'a' in a
is done and result is pushed onto the stack i.e True
. Now stack has TOS as True
and duplicate reference from DUP_TOP
below it.
JUMP_IF_FALSE_OR_POP
: If TOS is false, sets the bytecode counter to target and leaves TOS on the stack. Otherwise (TOS is true), TOS is popped. In our example, TOS
is True
so. TOS
is popped. Now TOS
is a
.
LOAD_CONST
True
is pushed onto the stack. COMPARE_OP
==
. True==a
is done which False
. Now TOS
is False
.
RETURN_VALUE
: Returns with TOS to the caller of the function. In our example, TOS
is False
at this point. False
is returned.
POP_TOP
: Removes the top-of-stack (TOS) item.
The only difference between both the expressions is that a
is evaluate twice in the 2nd one.
Also refer to this answer: https://stackoverflow.com/a/3299724/12416453