Python “is” and “is not”: Explained Using 14 Examples!

In this article let us learn about the “is” and “is not” operators in Python.

The first step in the journey towards mastery of any programming language is to learn about the various operators provided by that language and learn how to wield them. Python is no exception to this rule!

Every programming language comes in-built with

  • arithmetic operators for addition, subtraction, multiplication and division operations, and
  • logical operators for AND, OR, NOT and XOR operations.

But since Python is a language that focuses on readability we have more operators than the usual ones which programmers can benefit from. Two good examples of such operators are the “is” and “is not” operators.

Even though the concepts might look simple, our brains are really good at understanding the concepts but not so good at remembering them!

The best trick to make our brains remember stuff is via active learning. By “active learning” I mean “doing”!!

So put on your coding hats, open your laptops and start experimenting and playing with the code shown in the examples as you read them!

The phrase “Practice Makes Perfect” did not survive so many centuries for no reason!

For those of you who came here just to refresh your memories, here is a Cheatsheet!

Python “is” and “is not” Operators: Cheatsheet

The table below shows the meaning and usage of the “is” and “is not” operators

OperatorMeaningExample
isis the same object as>>> string1 = “apple”
>>> string2 = “orange”
>>> string1copy = string1
>>> string1 is string1copy
True
>>> string1 is string2
False
is notis not the same object as>>> string1 = “apple”
>>> string2 = “orange”
>>> string1copy = string1
>>> string1 is not string2
True
>>> string1 is not string1copy
False

What does “is” in Python do? The “is” operator is used to verify if 2 references are pointing to the same object.

What does “is not” in Python do? The “is not” operator is used to verify if 2 references are not pointing to the same object.

Essentially the “is not” operator does the opposite of what the “is” operator does.

Since these 2 operators are checking the identity of the given objects for equality these are also called as identity operators.

If the words “references” and “objects” in the short answers above are causing more confusion than explanation, then you are not alone!

The answers above are aimed at those people who are familiar with those terms as those terms are common across many programming languages.

This article is specifically crafted keeping beginners in mind, so if you are feeling confused, forget that you ever read the answer above, find a quiet place, focus for the next 10 to 25 minutes and read the rest of the article, then come back and read the answers above, I guarantee they will make more sense!

Let us start this article by learning about “Objects” and “References” in Python!

Fundamentals Needed Before You Can Learn The “is” And “is not” Operators

Classes and Objects

Let us not take the academic approach and start this section off with a nice definition of objects. Instead, let us have a look at some examples to try and develop an intuitive feel for them!

Dog

If you are wondering What is the picture of a dog doing in an article like this? It is not there by mistake, it has been put there by design!

If someone asks you what animal is there in the pic above? you would say “dog

How did your brain know that the above picture is a “dog” and not “something else”?

Because the animal in the picture above matches all the characteristics of what we humans call a “dog”!

Hence we can say, a dog is an animal that has some characteristics of X, Y, and Z. Here X, Y, and Z can be a long snout, nose, etc!

In more formal words,

A dog is a class of pet characterized by X, Y and Z.

Now have a look at the next picture.

In the pic above we have a group of pets, each pet in the picture also match the characteristic of a dog, hence we can say that there are 3 pets of the type “dog” in the above picture.

Let us have a look at another example.

In the pic above we can see a bunch of cool devices from the future which we can classify as “Robots”. In other words,

These are electronic devices belonging to the “Robots” class

Each individual robot/device itself is an object

In computer languages, no matter whether we are looking at a robot or a dog (or a robot dog!) we call each individual item as an “object” belonging to a particular “class”

Objects: The tangible individual item

Class: The “Idea

Let us have a look at another picture just to make the concept of objects familiar

Class and objects example picture

In the pic above, we have 3 pets belonging to the class “Dogs”. Each pet is an individual object and collectively they all can be classified under the “Dogs” class.

In other words, Coco, Buster, and Buddy are objects belonging to the class “Dogs”

Objects: The tangible individual itemCocoBuster, and Buddy

Class: The “Idea: A dog is a class of pet characterized by X, Y and Z.

Let us have a look at one last example

Here on the left, we have a few apartments and on the right, we have a blueprint. Let’s call this Blueprint-A.

Each of the individual apartments is built using the same blueprint. Hence each individual apartment is an object belonging to the class “Blueprint-A”

Objects: The tangible individual itemApartments 1, 2, 3, 4

Class: The “Idea: Blueprint-A

This is a “hard to grasp” concept, but once you understand the idea behind it, you will never forget the concept!

If you are feeling confused, sit quietly for a moment and think about the examples I gave till the “Aha!” moment comes to you!

Once you are ready, read on!

Okay, let us open the Python interpreter and do some coding!

>>> x = 10
>>> a = "apple"
>>> l = [1, 2, 3]

Here we have created 3 variables.

  • The variable x holds the integer value 10
  • The variable a holds the string “apple” and
  • The variable l holds the list [1, 2, 3]

In the world of python whatever is held by a variable name is an “object”. In Example#1 above, 10 is an integer object, “apple” is a string object, and [1, 2, 3] is a list object.

You can see “what type an object is” using the aptly named built-in function “type()” as shown in Example#2 below.

>>> type("apple")
<class 'str'>
>>> type(10)
<class 'int'>

As you can see the integer 10 is of type int, short for integer, and the word “apple” is of type str short for string.

Objects and References

Alright now that we have understood what classes and objects are, let us learn about what references are and how they are connected to objects!

As you can see there are 3 men in the picture, and each one has a name.

Now consider the “Mathew”, he can be also called with the name “Matt”. So no matter if you use the name “Mathew” or “Matt” they both refer to the same guy in the brown suit!

The same goes with “Thomas” a.k.a “Tom” and James a.k.a Jim.

Let us write a simple program to see what I mean

Mathew = "the guy in the Brown Suit"
Matt = Mathew

Thomas = "the guy in the Blue Suit"
Tom = Thomas

print("Mathew is ", Matt)
print("Tom is ", Thomas)

Okay, now that you have read the code, time for a challenge!

Before reading on, try to answer this question!

What output do you think this code will print?

Alright, now let us see if you got the answer correct!

This will give an output like this

Mathew is the guy in the Brown Suit
Tom is the guy in the Blue Suit

As you can see, it doesn’t matter whether you use the name “Mathew” or “Matt”, they both refer to “the guy in the Brown Suit”!

Hence we can say that

Mathew and Matt are references to the guy in the Brown suit

Whenever you create an object in Python, the object gets an “ID”, something like our social security number if you are in the USA or the personal ID code if you are in Europe.

If we want, we can also have a look at this “ID” using the id() function as shown below

>>> id(Mathew)
139633218611568
>>> id(Matt)
139633218611568

As you can see they both have the same “ID” number!

This is what we want as they are both referring to the same person!

I leave it up to you to verify if the ID for (Tom, Thomas) and (Jim, James) are the same!

We refer to “Mathew” as the formal name and “Matt” as the nickname.

In the computer programming world, the names which are referring to an object with a given ID are called “References”!

How are ID numbers generated uniquely for each object?

These ID numbers are basically the memory location in which an object is stored.

You can think of “Memory location” as a book slot number in a library, only one book can occupy a given book slot, similarly, only one object can occupy a memory slot,

That is how python ensures that a given “id()” is always unique!

This is how Python works under the hood to model the real world inside computers using just 0’s and 1’s!

In summary,

Objects are the values stored in memory, references are the names using which we refer to those objects in our program

Alright, now that we have understood what classes, objects, and references are, we are all set with the fundamentals!

From this point, our journey to learn what “is” and “is not” does is going to be a simple one!

The “is” operator in Python

Let us take our same “Matt” and “Mathew” example. Say I ask you a True or False question

is Matt and Mathew the same person?

You would say “True“. Python does the exact same this using the “is” operator!

>>> Matt is Mathew
True

Now if I ask

is Tom and Mathew the same person,?

you would say “False“.

>>> Tom is Mathew
False

Simple as that!

Thus, the answer to the question “What does “is” in Python do?” is

The “is” operator is used to verify if 2 references are pointing to the same object.

Next, let move on to the “is not” operator.

The “is not” operator in Python

Taking the same example,

# Example 6
>>> Matt is not Thomas
True
>>> Mathew is not Matt
False

As you can see, the “is not” operator does the exact opposite of what the “is” operator does!

Thus the answer to the question “What does “is not” in Python do?” is

The “is not” operator is used to verify if 2 references are not pointing to the same object.

See how easy it is once we have understood the fundamentals!

Now that we have learned what these operators do, let us take the next step towards mastery and learn how to use these operators in our programs!

When and Where To Use “is” And “is not” Operators?

As a beginner Python programmer, you will not see much use for the “is” and “is not” operators. But the developers of the Python programming language felt that these are necessary parts of the language for a reason, as without these operators

  • there are many pitfalls that can lead a programmer down to buggy roads
  • these operators can vastly improve the readability of our code.

Read on to understand what kind of pitfalls you can avoid and how you can leverage these operators to make your code more readable.

A good time to use the “is” operator

is Keyword Use-Case#1: Type Checking

Consider the simple example below.

x = "apple"
y = 1

if type(x) is str:
  print("x is a string!")

if type(y) is int:
  print("y is an integer!")

This gives an output like this

x is a string!
y is an integer!

As you can see both the print statements got executed, which means both the conditions in the if statement got evaluated to be True

Unlike the other examples, instead of comparing the ID of 2 objects, we are comparing the ID of 2 types this time!

>>> id(type(x))
>>> id(type(x))
9484384
>>> id(str)
9484384

As you can see even the “object types” like “str” have IDs and these IDs match with the name of the “type” (str in the example above).

Okay, the next question that pops into our heads is

Where is this property actually useful in our programs?

Assume we have a function that calculates the area of a square when the side is given as input.

def calculateAreaOfSquare(side):
  if (type(side) is int) or (type(side) is float):
    print("Area = ", side*side)
  else:
    print("Invalid Input to the function")

We expect the user of this function to provide either an integer or a float as input. To make sure that the input is valid we are using the built-in type() function along with the “is” operator as shown above.

Take a minute or 2 to understand what is going on. Open your editor and try out the example yourself before you look at the output!

No great programmer has achieved greatness just by reading!

So, GO DO SOME CODING!

Using the function will give an output as shown below.

>>> calculateAreaOfSquare(4)
Area =  16
>>> calculateAreaOfSquare(5.5)
Area =  30.25
>>> calculateAreaOfSquare("five")
Invalid Input to the function

As you can see in line-5 above when an invalid argument is provided to the function, our function catches it using the type() function and the is operator and prints “Invalid Input to the function“.

Hence,

Type checking is not done by default in python functions, the “is” operator is very useful in such scenarios to make sure that the arguments received are valid.

is Keyword Use-Case#2: Check if a given object is same as None

Another place where you should consider using the “is” operator is when comparing an object to “None” or “NotImplemented

In case you are not familiar with the “None

None” is a keyword in Python, similar to “NULL” in other languages, used to note the absence of a value.

Let us have a look at a simple example.

def divide(x,y):
  if y != 0:
    return x/y
  else:
    return None

The above function is a very simple function, which

  • takes in 2 numbers,
  • divides the 1st number by the 2nd, and
  • returns the result.

We know that in math, dividing by zero is illegal, and hence we return None if the 2nd number is 0.

Now we can use the function like this.

# Get 2 numbers as input from the user
x = float(input("please enter the 1st number: "))
y = float(input("please enter the 2nd number: "))

quotient = divide(x,y)

if quotient is None:
  print ("Divide by Zero is not allowed")
else:
  print ("x/y = ", quotient)

A Challenge for you!

Before looking at the output, I want to challenge you to compute in your heads and predict what the code will print!

These thinking exercises will condition your brain to think like a programmer!

Are you ready? Okay, time to see the output!

please enter the 1st number: 2.5
please enter the 2nd number: 5
x/y =  0.5

please enter the 1st number: 5
please enter the 2nd number: 0
Divide by Zero is not allowed

This way we can make use of the “is” operator to check if a given object’s value is “None”.

is Keyword Use-Case#3: Check if a given object is same as NotImplemented

Now let us see one last example of using the “is” operator with “NotImplemented“.

In case you are not familiar with the “NotImplemented

NotImplemented” is a keyword in Python, used to denote that some “expected functionality” is not implemented in the code.

Consider the function below

def square_root(x):
  if x >= 0:
    return x**0.5
  else:
    return NotImplemented

I assume you know that the square root of a negative number is a complex number (if you didn’t you do now 😉 )

Our programmer is a little lazy, so he programmed the square_root() function to only calculate roots of positive numbers.

You can use the function in your code like this.

print("This program will calculate the square root of any given number!")
x = float(input("please enter a number: "))

y = square_root(x)

if y is NotImplemented:
  print("Our programmer is lazy, please use only positive numbers")
else:
  print(f"Square root of {x} is {y}")

Running the code above will give an output like this!

please enter a number: 25
Square root of 25.0 is 5.0
please enter a number: -50
Our programmer is lazy, please use only positive numbers

Why not use the == operator with None and NotImplemented?

We could have used the “==” operator with both None and NotImplemented and have gotten the exact same result, but using the “is” operator makes the code more readable hence whenever you come across a situation where you might need to use None or NotImplemented, the official python documentation PEP8 recommends we use the “is” operator!

In case if you are not familiar with the “==” operator, then pause this article here and check out the following one where I have explained everything you need to know about the equality operator.

Python’s ‘==’ Operator: Meaning and Usage Explained with Examples

The reason behind that can be explained using the following examples

Consider the code below.

>>> obj1 = None
>>> obj1 == None
True
>>> obj1 is None
True

Everything works fine, no issues whatsoever here!

Now consider a class like below with the stupidest-ever equality function definition.

# A bad class that always return true no matter what!
class BadAtEquality():
  def __eq__(self, object):
    return True

This class overrides the “==” operator with a stupid function, which always returns true no matter what the object is compared with!

If we use this function in code we get something like this

>>> obj1 = BadAtEquality()
>>> obj1 == "apple"
True
>>> obj1 == [1, 2, 3]
True
>>> obj1 == None
True
>>> obj1 is None
False

The situation in Lines 2 to 7 in the session above is what we are trying to avoid!

If we wanted to compare an object with None, we better go with the “is” operator instead of using the “==” operator to avoid unnecessary surprises!

These are the types of pitfalls Python aims to avoid with the help of the “is” and “is not” operators.

Shout out to Alok Singhal at stackoverflow.com for this nice example!

The reason the is operator works is due to the fact

None” and “NotImplemented” objects are singletons in Python, meaning only one of these objects will be present in the memory!

Hence, because of the facts

  • the equality operators can always be customized to give out anything we want it to, and
  • there is only one “None” object in the memory, we should always use the “is” operator with None and NotImplemented.

A good time to use the “is not” operator

Similar to the “is” operator, whenever you need to compare something to a singleton object like “None” or “NotImplemented” go with “is not“.

As “is not” is basically a negation of “is“, all the examples in the previous section will work here too!

At the risk of repeating myself let us take a look at the same square_root() example

def square_root(x):
  if x >= 0:
    return x**0.5
  else:
    return NotImplemented


print("This program will calculate the square root of any given number!")
x = float(input("please enter a number: "))

y = square_root(x)

if y is not NotImplemented:
  print(f"Square root of {x} is {y}")
else:
  print("Our programmer is lazy, please use only positive numbers")

The above example is the same as Example#10.2 but uses the “is not” operator instead of the “is” operator.

When to use which one depends on the situation and whichever makes the code more readable. As you get more experience as a Python programmer, you will intuitively know whether to use “is” or “is not” in a given situation.

If you have read this far, then bravo! I admire your hunger for knowledge!

In an attempt to quench your thirst, I will try to give you one more interesting fact about the “is” and “is not” operator!

How are the “is” and “is not” operators implemented under the hood?

Time for another challenge!

How do you think the “is” and “is not” operators are implemented under the hood?

Before reading on, take 2 mins and think! I am sure the answer will come to you!

Alright, now let us see if you got the answer correct!

These are basically implemented using the built-in id() function as seen above.

So when you write

a is b

Python translates this to

id(a) == id(b)

and when you write

a is not b

Python translates this to

id(a) != id(b)

As you can see the “under the hood” implementation is fairly straightforward!

We can use the “id()” functions directly but that would make the code harder to read!

Remember, Python is all about Readability!

If you are not clear on how the “==” and “!=” operator works, we have separate articles for those which you can read in the links below.

Python: “is” vs “==” Similarities and Differences

Python: “is not” vs “!=” Similarities and Differences

Where To Go From Here?

Bravo again! I admire your hunger for learning, and your spirit to go over obstacles to achieve mastery in your craft!

At this point, I suggest you play around with these operators till they become second nature.

Then go ahead and try reading the cheatsheet at the beginning of the article again, I am sure this time it will make sense!

Once you feel you have mastered these operators, go ahead and choose your next read from the “Related Articles” section below!

I hope you found this article useful.

Feel free to share this article with your friends and colleagues!

Related articles

Python: “is” vs “==” Similarities and Differences

Python: “is not” vs “!=” Similarities and Differences

Python “in” and “not in”: Explained Using 8 Examples!

Python’s ‘==’ Operator: Meaning and Usage Explained with Examples

Python’s ‘!=’ Operator: Meaning and Usage Explained with Examples

References

  1. Operators
  2. Expressions
  3. PEP8
  4. StackOverflow Question

4 thoughts on “Python “is” and “is not”: Explained Using 14 Examples!”

Comments are closed.