How to immutable object is set in memory with Python

4 Answers

0 votes
n = 7

print("id: ", id(n))

n = 9

print("id: ", id(n)) # 7 is created in new memory location because n is immutable



'''
run:

id:  140624749786592
id:  140624749786656

'''

 



answered Aug 10, 2022 by avibootz
edited Aug 10, 2022 by avibootz
0 votes
n = 7

print("id: ", id(n))

x = n

print("id: ", id(x)) # n and x point to the same memory location



'''
run:

id:  139859162949088
id:  139859162949088

'''

 



answered Aug 10, 2022 by avibootz
0 votes
n = 7

print("id: ", id(n))
print("id: ", id(7))

x = n

print("id: ", id(x)) # n and x point to the same memory location

n = n + 3
print("id: ", id(n)) # n + 3 is created in new memory location because n is immutable
print("id: ", id(x)) # x stay in the same memory location




'''
run:

id:  140425428280800
id:  140425428280800
id:  140425428280800
id:  140425428280896
id:  140425428280800

'''

 



answered Aug 10, 2022 by avibootz
0 votes
lst = [1, 2, 3, 4, 5]

print(lst) 
print(id(lst))

lst[2] = 99

print(lst) 
print(id(lst))

lst.append(800) 

print(lst) 
print(id(lst)) # lst stay in the same memory location




'''
run:

[1, 2, 3, 4, 5]
139633638018624
[1, 2, 99, 4, 5]
139633638018624
[1, 2, 99, 4, 5, 800]
139633638018624

'''

 



answered Aug 10, 2022 by avibootz

Related questions

1 answer 71 views
1 answer 90 views
90 views asked Mar 18, 2023 by avibootz
1 answer 150 views
1 answer 109 views
109 views asked Mar 18, 2023 by avibootz
1 answer 223 views
1 answer 149 views
...