0

I know this has been asked like a million times. Somehow am not convinced with the answers(pl forgive me). I have written the following sample code.

class Equals:

    def checkEquals(self, element1, element2):

        return element1 == element2

    def checkIs(self,element1,element2):

        return  element1 is element2


e = Equals()
x = 1000
y = 1000
print x
print y
print id(x)
print id(y)
print e.checkequals(x,y)
print e.checkis(x,y)

Here is the output.

1000
1000
37695976
37695976
True
True

Now my questions are.

  1. Though x and y values are same, Shouldnt they be placed in different memory locations unless x = y = 1000? Why are they placed in the same location? I believe thats why x is y returns True.

  2. And in the same program if I give x = [10,20] , y = [10,20] both have different memory locations. Why is that so?

I have observed the same concept in java as well for "==" as they are comparing the memory location of the objects. Thats the reason I had to revisit this in python as well.

DineshKumar
  • 1,599
  • 2
  • 16
  • 30
  • 3
    This was answered just yesterday (again, I must add). Both x and y are module-level statements and the Python compiler re-uses the same constant object to set these. – Martijn Pieters May 11 '16 at 15:20
  • `x` and `y` aren't locations, they are names. In your 1st example, both names are bound to an immutable integer object with value 1000, so Python is smart enough to bind those names to the same object. You may find this article helpful: [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html), which was written by SO veteran Ned Batchelder. – PM 2Ring May 11 '16 at 15:34
  • @PM2Ring Yeah they are not locations. But what I meant was "is" will compare the memory locations of the objects. That's why I have printed id(). Thanks for the article.I am going through it now. – DineshKumar May 11 '16 at 15:40

0 Answers0