0

Someone said to me Everything in python is an object. Like the example below, python just points to the same address for the same value.

a = 1
b = 1
print(id(a), id(b)) # Same!
print(a is b) # True

But this rule seems like not being applied a list.

a = [1]
b = [1]
print(id(a), id(b)) # !=
print(a is b) # False

I tested this for a Tuple, but it also didn't work. So I guess it's not about whether they are mutables or not. Why does this happen?

Inhyeok Yoo
  • 133
  • 7
  • 1
    integers from -5 to 256 are interned in CPython. see e.g. here: https://www.codesansar.com/python-programming/integer-interning.htm – hiro protagonist Oct 23 '20 at 06:32
  • See [`is` operator behaves unexpectedly](https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers), [is there a difference between `==` and `is`](https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is), ...etc. – trincot Oct 23 '20 at 06:37
  • see also here: https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong – hiro protagonist Oct 23 '20 at 06:38
  • 1
    Keep in mind that we need ways to have lists that have the same elements but are different. Imagine we had only one empty list and if we created three and added elements to one, the other two would have the same elements. That problem can’t happen with immutable datatypes since they do not change. When you add ints you get a new one. Rather than a mutated version of the old int. – Lukas S Oct 23 '20 at 06:45
  • @hiroprotagonist who did close the question? The question also happens in the case of string. Moreover, the sentence "Everything in python is an object" isn't correct when both a and b are larger than 255 since they have to indicate the same 'object'. – Inhyeok Yoo Oct 25 '20 at 11:33
  • Please dudes, read the lines. The question is about "Everything of python is an object". – Inhyeok Yoo Oct 25 '20 at 11:41
  • @user2640045 you mentioned *That problem can’t happen with immutable datatypes since they do not change.*, then why two tuple doesn't have the same address? – Inhyeok Yoo Oct 25 '20 at 11:41
  • 1
    @InhyeokYoo I don't see how "everything is an object" is related to things having the same address. By __that problem__ I am talking about the problem with mutable datatypes I mentioned right before it. – Lukas S Oct 25 '20 at 11:53
  • everything in python is an object. but CPython chooses to intern some of them (i.e. make them behave like singletons [which still are objects]). small integers and short strings are examples. – hiro protagonist Oct 25 '20 at 12:47

0 Answers0