开发者

Python: print "word" in [] == False

Going a bit mental here tryin开发者_开发问答g to work out what this does in python:

print "word" in [] == False

Why does this print False?


Perhaps a more clear example of this unusual behaviour is the following:

>>> print 'word' in ['word']
True
>>> print 'word' in ['word'] == True
False

Your example is equivalent to:

print ("word" in []) and ([] == False)

This is because two boolean expressions can be combined, with the intention of allowing this abbreviation:

a < x < b

for this longer but equivalent expression:

(a < x) and (x < b)


Just like you can chain operators in 23 < x < 42, you can do that with in and ==.

"word" in [] is False and [] == False evaluates to False. Therefore, the whole result is

"word" in [] == False
"word" in [] and [] == False
False and False
False


Just to add to Mark Byers great answer

>>> import dis
>>> dis.dis(lambda: 'word' in [] == False)
  1           0 LOAD_CONST               1 ('word')
              3 BUILD_LIST               0
              6 DUP_TOP             
              7 ROT_THREE           
              8 COMPARE_OP               6 (in)
             11 JUMP_IF_FALSE_OR_POP    21
             14 LOAD_GLOBAL              0 (False)
             17 COMPARE_OP               2 (==)
             20 RETURN_VALUE        
        >>   21 ROT_TWO             
             22 POP_TOP             
             23 RETURN_VALUE        
>>> dis.dis(lambda: ('word' in []) == False)
  1           0 LOAD_CONST               1 ('word')
              3 LOAD_CONST               2 (())
              6 COMPARE_OP               6 (in)
              9 LOAD_GLOBAL              0 (False)
             12 COMPARE_OP               2 (==)
             15 RETURN_VALUE        
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜