0

What is the output and why

a = "hello_world" b = "hello_" + "world" print(a is b)

27th Jun 2025, 12:50 PM
Mandar Kulkarni
2 Respostas
+ 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/
27th Jun 2025, 2:20 PM
Bob_Li
Bob_Li - avatar
+ 2
What do you think and why don't you try?
27th Jun 2025, 1:19 PM
Lisa
Lisa - avatar