2015年5月5日 星期二

[ Python 常見問題 ] Difference between '==' and 'is' operator

Source From Here
Question
I've got a python program where two variables are set to the value 'public'. In a conditional expression I have the comparison var1 is var2 which fails, but if I change it to var1 == var2 it returns True. now if I open my python interpreter and do the same "is" comparison it succeeds:
>>> s1 = 'public'
>>> s2 = 'public'
>>> s2 is s1
True


How-To
is is identity testing, == is equality testing. what happens in your code would be emulated in the interpreter like this:
>>> a = 'pub'
>>> b = ''.join(['p', 'u', 'b'])
>>> a == b
True
>>> a is b
False

Supplement
Is there a difference between `==` and `is` in Python?
is will return True if two variables point to the same object== if the objects referred to by the variables are equal (__eq__).


沒有留言:

張貼留言

[ Python 文章收集 ] Function Composition in Python

Source From  Here   Preface   While I don’t consider myself a functional programming guru, all those hours spent in Haskell, Lisp and Scheme...