Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

Going a bit mental here trying to work out what this does in python:

print "word" in [] == False

Why does this print False?

like image 946
Tom Viner Avatar asked Dec 07 '22 19:12

Tom Viner


2 Answers

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)
like image 119
Mark Byers Avatar answered Jan 29 '23 23:01

Mark Byers


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
like image 33
phihag Avatar answered Jan 29 '23 23:01

phihag