is
and ==
are not the same.
==
checks for quality and is
checks for identity.
identity
is the current address value.
So the question of which way is better is different depending on the case.
Please refer to the examples below in which is
and ==
produce different results.
If you look at the example,
str1 = "cat"
str2 = "".join("cat")
str3 = "".join(['c','a','t'])
print "str1 == str2:", str1==str2
print "str1 is str2:", str1 is str2
print "\nstr3 == str1:", str3==str1
print "str3 is str2", str3 is str2
print "\nid of str1:", id(str1)
print "id of str2:", id(str2)
print "id of str3:", id(str3)
Result:
str1 == str2: True
str1 is str2: False
str3 == str1: True
str3 is str2 False
id of str1: 4463102912
id of str2: 4463847504
id of str3: 4463847664
© 2024 OneMinuteCode. All rights reserved.