0

I tried in Jupiter it gives me the answer same id for integer

a=10
b=10
print(type(a))
print(type(b))
print(id(a))
2835524512336
print(id(b))
2835524512336

a=10.5
b=10.5
print(type(a))
print(type(b))
print(id(a))
2835627979536
print(id(b))
2835626077552

And in float case it gives another result, can you tell me why and in thonny gives same result for both integer and float case

wovano
  • 4,543
  • 5
  • 22
  • 49
pika
  • 1
  • 2
  • Does this answer your question? [Why does the \`is\` operator behave differently in a script vs the REPL?](https://stackoverflow.com/questions/55347581/why-does-the-is-operator-behave-differently-in-a-script-vs-the-repl) – wovano Apr 26 '22 at 08:39
  • Also related: https://stackoverflow.com/questions/53168093/integer-caching-for-numbers-greater-than-256-and-less-than-5 and https://stackoverflow.com/questions/56464966/why-does-python-not-cache-integer-values-outside-the-range-5-256 – wovano Apr 26 '22 at 08:40
  • This is probably the best dupe target: https://stackoverflow.com/questions/15996984/why-id-function-behaves-differently-with-integer-and-float – wovano Apr 26 '22 at 08:57

2 Answers2

0

That happens because Python caches all integers from -5 to 256, booleans and some other stuff at start.

>>> a = 256
>>> b = 256
>>> id(a)
9797120
>>> id(b)
9797120
>>> a = 257
>>> b = 257
>>> id(a)
139728946864048
>>> id(b)
139728946426032
>>> 
sudden_appearance
  • 1,968
  • 1
  • 4
  • 15
0

If we refer to this answer:

Every variable in Python is an object, integer and float are then object.

However small integers are pre-allocated -> their id is fixed by the Python interpreter. Thus they are shared between references to the same object (in your case a and b).

It may be to ease memory management with small integers that are often used (e.g. -5 to 256 in this case of Python interpreter, search small_ints and _PY_NSMALLNEGINTS, _PY_NSMALLPOSINTS)

Bastien
  • 1
  • 1