Two variables point to same string value but address in memory are different. Why pls?

Two variables point to same string value but address in memory are different. Why pls?
0

school = “PadhAI Data Science”
print(school)
print(type(school))
RollNo = 30216
print(type(RollNo))
Experience=12.6
print(type(Experience))
#where the object in memory is stored
print(id(school))
print(id(Experience))
print(id(RollNo))
another_school = “PadhAI Data Science”
print(another_school)
#memor location of two variables having the same string

print(id(school))
print(id(another_school))

Result

PadhAI Data Science
<class ‘str’>
<class ‘int’>
<class ‘float’>
140685788605008
140685798038336
140685789043216
PadhAI Data Science
140685788605008
140685787919968

1 Like

In Python, if the length of string/float/int is small up to (3 to 4 digit) and both variables point to the same object then the python interpreter creates one object in heap.
Ex:
x = 5
y = 5
x == y #true
if the length of the string/float/int is big (more then 4 digit) and both variables points to same object then python interpreter does not check if there is an object with same value in heap, it directly creates new object even if there was object present with same value.
Thats why addresses are different

4 Likes

great, thanks Vikash !

I noticed that in the example given in the video, the length is 6 characters but still it is pointed to same object. Kindly can you explain that as well.

Looks like it is not linked to length or number of digits.
str1 = “datascience”
str2 = “datascience”
str3 = “data”
str4 = “data”
str5 = “science”
str6 = “science”

print(id(str1))
print(id(str2))
print(id(str3))
print(id(str4))
print(id(str5))
print(id(str6))

140530204006896
140530204006896
140530786542736
140530786542736
140530203748872
140530203748872

It has an issue of pointing to different memory reference ID if there is a space in string.

This is linked to STRING INTERNING concept of Python. Python first checks its memory for identical immutable objects before instantiating new ones.

Refer link - https://medium.com/@bdov_/https-medium-com-bdov-python-objects-part-iii-string-interning-625d3c7319de

2 Likes