Hackernoon logoDemysti-py: “==“ vs “is“ by@pylearn.live

Demysti-py: “==“ vs “is“

Most novice programmers when using these comparison operators believe they are the same thing. You’ll probably find they give the same answer in most cases but there will come a time when that isn’t the case and you’ll be left scratching your head. Today I want to clear up that misunderstanding.

Let’s see where these operators will give the same answer and where they won’t.

>>> a = [1, 2, 3, 4]
>>> b = a
>>> a == b
True
>>> a is b
True

So what’s the difference? Let’s look at another example:

>>> a = [1, 2, 3, 4]
>>> b = [1, 2, 3, 4]
>>> a == b
True
>>> a is b
False

That’s some interesting behavior. Let’s take a closer look at whats going on under the hood. I’d like to point out, that Python lists are a lot more complicated than arrays but I will not be talking about their CPython implementation here. However if you are interested in understanding how they are implemented I highly recommend checking out this post by Laurent Luce.

When you assign a list to a variable, a like in the above example, Python allocates memory for that list BUT the actual list isn’t what is stored in our variable. Instead, Python creates a list object and stores a reference to that object in the variable. Essentially our variable now points to the list as seen below:

‘a’ references (points to) a list

In our first example we said b = a. This means that b is referencing a which references our list object. They are now referencing the same object.

‘a’ and ‘b’ reference (point to) the same list

Now to distinguish ‘==’ and ‘is’.

‘==’ checks for equality. Let’ say we had a factory producing T-Shirts. If two T-Shirts are produced and held next to each other, we couldn’t tell them apart. So we would say the two T-Shirts are ‘==’.

‘is’ checks for identity. With our two T-Shirts, we know they are not the same thing. So we would say that T-Shirt 1 is T-Shirt 2 is false.

With python, it’s basically the same thing except with the ‘is’ operator we check references.

In our first example, ‘a == b’ returns true because what ever a is referencing contains the exact same things that b is referencing AND ‘a is b’ returns true because both a and b are referencing the same list object.

However, with our second example we said a = [1, 2, 3, 4] and b = [1, 2, 3, 4]

This creates a list object and stores a reference to it in a, then it creates a second list object and stores a reference to it in b.

‘a == b’ is still true. However, ‘a is b’ is now false. This is because both a and b now reference different objects. This can be observed below:

‘a’ and ‘b’ reference (point to) different list objects.

In summary

  • ‘is’ returns True if the operands reference the same object.
  • ‘==’ returns True if the contents of the objects referenced by the operands are equal.

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.