表面上is和==都是用来测试相等性,可是它们却很不一样。
==操作符测试值的相等性。
is表达式测试对象的一致性。
==递归地比较所有内嵌对象。is测试二者是否是同一个对象,也就是说,在同一个内存地址中。


list1和list2创建了两个对象,在内存中分别存在两个地址存储这两个对象。


按理来说这是两个截然不同的对象碰巧有着相同的值,那么==应该为真,is应该为假。但结果却是都为真。原因是为什么呢?
这是因为在Python内部暂时存储并重复使用短字符作为最佳化,事实上内存里只有一个字符串供str1和str2分享。因此结果都为真。
为了得到一般的结果,需要使用更长的字符串。
网友评论