Interesting Python Operators

Have you noticed that + (arithmetic operation) creates a new object with a different identity when it works with a variable while + (string concatenation) doesn’t do so? (You can use the id() function and the identity operator is to find out.)

x = 1000
y = 3 * 4 + 125 * 8 - 6 * 2
z = x + 0

print(id(x))  # 4305146928
print(id(y))  # 4305146928
print(id(z))  # 4305147280
print(x is y)  # True
print(y is z)  # False
print(x is z)  # False

str1 = "Hello!!!"
str2 = "He" + "l" * 2 + "o" + "!" * 3
str3 = str1 + ""

print(id(str1))  # 4306878512
print(id(str2))  # 4306878512
print(id(str3))  # 4306878512
print(str1 is str2)  # True
print(str2 is str3)  # True
print(str1 is str3)  # True

Let’s look at another snippet:

import math
a = math.sqrt(2)
b = math.sqrt(2 + 0)

print(id(a))  # 4338072464
print(id(b))  # 4339094832
print(a == b)  # True
print(a is b)  # False

If recalling the math.sqrt() function creates a new instance with a different identity, then why does the len() function not do the same?

c = 1
d = len(str(c))

print(id(c))  # 4338057456
print(id(d))  # 4338057456
print(c == d)  # True
print(c is d)  # True

It’s really interesting. I can’t stop thinking about it.

Leave a Reply

Your email address will not be published.

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL and press the [Ping me!] button down there. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again.