-1

I came to know that any object in python has the same id irrespective of the place it is used.

a=5
print id(5)==id(a)

This statement prints True.

a='hillo'
b='hello'
c=b.replace('e','i') #this gives c='hillo'
print id(a)==id(c)

This statement prints False. But why?

Tonechas
  • 13,398
  • 16
  • 46
  • 80

2 Answers2

1

I came to know that any object in python has the same id irrespective of the place it is used.

That statement is completely false.


Small integers have their ID based on their immutable value and first occurrence in the program, because their values are small and Python caches them. That is why your first example returned True.

However, in your second example, you are comparing the IDs of two different (immutable) Strings, and that's why it returns False. In general, a new String (literal) instance creates a new String object each time, hence creating a different ID.

Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44
0

As String are in python, method replace() returns a copy of the string to another address in which the occurrences of old have been replaced with new. That's why there are two different id. Another similar case:

>>> p = "ooo"
>>> q = "ooovooo"
>>> r = p + "vooo"
>>> r
'ooovooo'
>>> q
'ooovooo'
>>> id(q) == id(r)
False

Python assign new address to r where concatenation of p and "vooo". Thats why both are different string.

Saket Mittal
  • 3,726
  • 3
  • 29
  • 49