Memory address in python

if x =10.4
y=10.4
why it will show different memory address?

2 Likes

@Pradhansuchismita97

when you assign the value 10.4 to the variable x, Python creates a new float object in memory with the value 10.4 and assigns the variable x to reference that object. Similarly, when you assign the value 10.4 to the variable y, Python creates another new float object in memory with the value 10.4 and assigns the variable y to reference that object.

Since x and y are two separate variables that reference two different objects in memory, they will have different memory addresses. This is because the memory addresses are the unique identifiers of the objects in memory.

1 Like

but sir in integer and string case why it shows same memory address?in integer it does not creat another value in new location, in float and other it does?

1 Like

@Pradhansuchismita97
Yes
For integers, Python caches a range of small integers (-5 to 256) and reuses them whenever they are needed. This means that if you assign the same integer value within this range to two different variables, they will have the same memory address.
Example:
x = 100
y = 100

print(id(x))
print(id(y))
This will output the same memory address for both x and y because the value 100 is within the cached range.

However, for larger integers or integers outside of the cached range, Python will create a new object in memory for each assignment
Example:
x = 1000
y = 1000

print(id(x))
print(id(y))
This will output different memory addresses for x and y because the value 1000 is outside of the cached range.

For strings, Python uses a similar caching mechanism for short strings (one character strings and strings with length up to 20), but creates new objects in memory for longer strings or strings with certain characters.

Hope you understand now

1 Like