1

I found a very strange interview question, at least for me.

If we declare the following variables, how many objects were created?

a=300, b=300, c=5, d=5
  • Can someone please explain this?
  • I am not sure to which segment in Python this is related to?
  • Is it maybe to memory management in Python?
S3DEV
  • 8,768
  • 3
  • 31
  • 42
Veljko
  • 1,708
  • 12
  • 40
  • 80
  • They're basically asking if `a` and `b` refer to the same object in memory (along with c and d) – Sayse Oct 24 '19 at 09:50
  • 1
    Possible duplicate of ["is" operator behaves unexpectedly with integers](https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers) – Nick is tired Oct 24 '19 at 09:53
  • Alternative duplicate target https://stackoverflow.com/questions/15171695/whats-with-the-integer-cache-maintained-by-the-interpreter – snakecharmerb Nov 03 '19 at 18:30

1 Answers1

6

There are 3 different objects, from the Python docs (Integer objects):

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.

UPDATE:

To answer the question explicitly, there are 3 different objects, but only 2 get created, namely, a and b. (Thanks to @jpa for pointing this out!)

gstukelj
  • 2,291
  • 1
  • 7
  • 20