0
What is the output and why
a = "hello_world" b = "hello_" + "world" print(a is b)
2 Antworten
+ 3
Google for:
Python interning
it will explain what's happening.
also, try this:
a = "hello_world"
b = "hello_" + "world"
c = "hello_"
c += "world"
print(a) #hello_world
print(b) #hello_world
print(c) #hello_world
print(id(a)) # some id
print(id(b)) # same as id(a)
print(id(c)) # different id
print(a is b) #True
print(a is c) #False
print(b is c) #False
Basically, concatenating the strings before assigning to variables as in a and b is the same as assigning the same string to both.
This results in the interning optimization being applied, so a and b gets the same address, because pointing to the same memory location is more efficient.
c is intitialized with a different string, so even if it eventually has the value of 'hello_world', it's id is different.
https://www.geeksforgeeks.org/python/object-interning-in-python/
+ 2
What do you think and why don't you try?