Skip to Content

Python’s “!=” Explained Using 12 Examples

Python’s “!=” Explained Using 12 Examples

In this article let us learn about the “!=” operator in Python and learn how to make use of this operator the same way the pros do!

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!

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’s “!=” Operator CheatSheet

What is “!=” in Python?Non-Equality Comparison Operator
How to read “!=”?“not equal to” or “not equal”
Use of “!=” operatorTo check if 2 objects are not equal in terms of value
How to read the code “x != y”is x not equal to y
Table#1: Python’s “!=” Operator CheatSheet

What is != in python? ‘!=’ is an operator in python which is used to compare the non-equality of 2 objects, be it strings or integers or some special user-defined classes

How to read “!= “? The “!=” symbol is called “not equal to” or “not equal” for short and is used in many programming languages like C, C++, Python, etc.

What is the != operator used for? The “not equal to” operator is a comparison operator used to compare 2 objects for non-equality.

Here is a simple example

Using ‘!=’ to check if 2 integer objects are not-equal to each other

>>> 1 != 2
True
>>> 2 != 2
False

In this simple session at the Python interpreter,

  • 1st line says “is 1 not equal to 2”, and as expected we get True
  • 3rd line says “is 2 not equal to 2” and as we expected we get False this time!

In simple words, if objects on either side of the “!=” operator are not equal we get True and if they are equal we get False

If you feel you have learned everything there is to know about the != operator, then hold your horses! There is plenty more to learn!

I urge you to call on your “virtue of patience” for another 15mins and read on! I promise you will learn a thing or 2 as we have merely scratched the surface!

I have divided this article into 4 levels as shown below.

  • Level#1: Beginner
  • Level#2: Intermediate
  • Level#3: Pro

Hence don’t worry if you have an ‘incomplete’ sort of feeling after reading the short answer above, as this article has been handcrafted to take you through the journey of learning from beginner to pro in just about 15-20 minutes and the cheatsheet above is just to get your feet wet!

Here is a short intro to the Python Interpreter. If you are already familiar with the interpreter, how to launch and use it, you can safely skip ahead to the next section!

Side Note: A Short Intro to the “Python interpreter

The Python interpreter, simply put, is the command line prompt “>>>” you will get when you enter the “python3” command in your Linux or Mac terminal (“3” stands for Python version 3).

This way of using python is also called using the “Interactive mode of the Python Interpreter”

$ python3
Python 3.8.10 (default, Sep 28 2021, 16:10:42) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

If you are in windows, you can open up the interpreter app by opening the command prompt and by entering the following command

>python
Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Here you can play around with any python program, one line at a time as shown below!

Python interpreter Example#1

You can even use this environment like a calculator by typing the expression to be evaluated as shown below!

Python interpreter as Calculator

I remember the first time I played around with the interpreter, it was loads of fun! To this day, it is still my go-to calculator app!

Go ahead, play a little with the interpreter! You can always bookmark this page and come back to it later!

Alright if you are done playing around with the interpreter let us go back to the main focus of this article, which is about learning the comparison operators.

Let us start our learning journey at Level#1 with a couple of examples!

LEVEL#1 (BEGINNER): Play with the “not equal to” (!=) operator one line at a time in the Python Interpreter

Let us have another look at the example in the cheatsheet

Using ‘!=’ to check if 2 integer objects are not-equal to each other

>>> 1 != 2
True
>>> 2 != 2
False

As we already saw, if objects on either side of the “!=” operator are not equal we get True and if they are equal we get False

So basically, if there is any expression of the form “x != y”, the Python will check both “x” and “y” and return True if x is not equal to y

Let us take a look at another example, this time with strings.

Example#2: Using “!=” to check if 2 strings are equal to each other

Next, let us take a look at another simple example of checking if 2 strings are equal to each other or not.

>>> str1 = "apple"
>>> str2 = "banana"
>>> str1 != str2
True
>>> str2 = "apple"
>>> str1 != str2
False

Before I explain what the code does, take a minute or 2 to understand what is going on. Open your Python interpreter and try out more examples yourself before you look at the explanation!

No great programmer has achieved greatness just by reading!

So, GO DO SOME CODING!

Okay, let us see what the above code does!

  • we assigned the string “apple” to the variable str1 and the string “banana” to the string str2.
  • then we are checking if variables str1 and str2 are not-equal and as expected the python interpreter prints out True.
  • then we have reassigned the variable str2 to “apple” and we are doing the same non-equality check once more. As expected we get False as the answer this time around!

Alright, now that we have seen some examples of how to use “!=” in the Python interpreter environment we have successfully completed LEVEL#1!

The time has come to use the “!=” operator in actual programs!

LEVEL#2 (INTERMEDIATE): Gain “Mastery” by using “!=” in Python programs!

Take a look at the following program.

Don’t feel intimidated to read code, at first it can be tough but sooner than you realize you will be reading code like you read plain English!

“!=” Usage in Python programs

yourCar = input("Please enter the name of your car's manufacturer: ")
yourFavCar = input("Please enter the name of your favorite car manufacturer: ")

if yourCar != yourFavCar:
    print("It is time to get a " + yourFavCar + "!!")
else:
    print("You have a great car!")

Here

  • We are getting 2 inputs from the user,
  • the first one asks the user’s present car manufacturer’s name and
  • the second one asks the user’s favorite car manufacturer’s name.
  • These 2 objects are then compared for inequality and
  • based on the the result we give some suggestions to the user.

Notice how the “!=” operator is used in line-4 for making the decision.

Using “==” to achieve the same result

One point worth noting is that the same example above can be written like this using the “==” operator as shown below

yourCar = input("Please enter the name of your car's manufacturer: ")
yourFavCar = input("Please enter the name of your favorite car manufacturer: ")
if yourCar == yourFavCar:
    print("You have a great car!")
else:
    print("It is time to get a " + yourFavCar + "!!")

In essence, where-ever the “!=” operator can be used in an if statement, the same result can be obtained by swapping the “if” and “else” content and using the “==” operator instead.

The operator “!=” basically does whatever “==” does and inverts the result. So whenever “==”returns True, “!=” returns False and vice versa.

When to use “==” and when to use “!=”?

When to use which one depends upon the situation and which one makes your code more readable.

In our example above, both the operators are okay in terms of readability.

Let us have a look at another example, where it makes more sense to use the “!=” character!

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
favNumStr = input("Choose your favorite number between 1 to 10: ")
favNum = int(favNumStr) # convert string to integer
print("Printing all numbers, except your favorite!")

for i in list1:
    if i != favNum:
         print(i)

The output of the above program will look like this

Choose your favorite number between 1 to 10: 4
Printing all numbers, except your favorite!
1
2
3
5
6
7
8
9
10

Here

  • we ask the user to choose a number between 1 to 10,
  • the user enters 4,
  • then we print all the numbers in 1 to 10 except 4.

Let us see how this same “for loop” will look if we use “==” instead of “!=”.

for i in list1:
    if i == favNum:
        continue
    else:
        print(i)

The output will look exactly the same as before

Choose your favorite number between 1 to 10: 5
Printing all numbers, except your favorite!
1
2
3
4
6
7
8
9
10

Both Examples 5.1 and 5.2 will work the same way.

But as you can see the first version of the for loop in Example 5.1 is way better as the code is shorter and more readable, and using “==” as shown in the second example is just not a good idea in this case.

Let us see one more example where != is the right operator choice

print("List Collection App, enter 'Done' when you are done! " )
entry = input("Please enter the first item in the list: ")
list1 = []

while entry != 'Done':
    list1.append(entry)
    entry = (input('Please enter the next item: '))

print("Here is your list")
print(list1)

Here

  • the user is asked to enter a series of items, and
  • when the user is done with their list we ask them to type the word “Done”.
  • Once the user is done we print the list out.

The output of the above program will look like this.

List Collection App, enter 'Done' when you are done!
Please enter the first item in the list: apples
Please enter the next item: milk
Please enter the next item: shampoo
Please enter the next item: cooking oil
Please enter the next item: onions
Please enter the next item: Done
Here is your list
['apples', 'milk', 'shampoo', 'cooking oil', 'onions']

Here the user enters a list of groceries to buy.

Maybe you can build a simple command-line app that will send out an email of the list to yourself as an exercise!

Let us try to rewrite the code using “==” instead

while True:
    list1.append(entry)
    entry = (input('Please enter the next item: '))
    if entry == 'Done':
        break

Which is not straightforward to read and it adds 2 more extra lines of code.

I hope now you get the need for the “!=” operator and you have understood where to use this operator in your code!

LEVEL#3: Become a Pro and gain full control of the “!=” operator and make it dance to your will!

Bravo if you have made it this far to Level#3! You really have a hunger for knowledge! Keep it up and you will become an expert python programmer very soon!

The time has come to take things to the highest possible level and learn how python implements the “!=” operator internally and see how we can modify this behavior to make python dance to our will!

How ‘!=’ is implemented in Python

Before starting to learn how “!=” is implemented inside Python, let us first learn a little bit about objects and methods in Python.

In Python all everything like integers, strings, lists, etc are Objects and all objects have some methods you can call to do some cool things with them. A good analogy would be

“methods” are like “dance moves” which a particular dancer (a given object) can do!

For example, consider the simple example below.

>>> string1 = "Hello Inventor!"
>>> string1.swapcase()
'hELLO iNVENTOR!'
>>>

Here the swapcase() method is used to make all uppercase letters into lowercase and vice versa!

If you wish to know what methods the string objects support, you can type the following command into the python interpreter.

>>> help(str)

You will get something like this

The screenshot below shows the usage of the help() command with the str type object

If you scroll a bit yourself, you will find yourself looking at a method named ne() as shown in the screenshot below.

This method is available for all built-in types like string, int, list, set, etc.

Let us try to understand what this method does!

As you can see from the example above, this method takes another object as an argument (the variable b in our case) and compares both of them for non-equality, which is the exact same thing our “!=” operator does!

ne stands for not-equal

>>> a = 20
>>> b = 10
>>> a.ne(b)
True

so in essence, whenever we use the operator “!=” in our code, python translates that to the form as shown above before executing the code!

so

a == b Becomes a.ne(b)

You might be thinking at this point “But what is the use of learning this detail?

Say you have your own class, which you wish to give to your friends, and you have your own logic of comparing 2 objects for non-equality. Then if you want the “!=” operator to work on your classes, you need to implement the ne() method in your own class.

Let us see how to do the same in the next section.

What is the default behavior of “!=” operator

According to python documentation

By default, object implements eq() by using is, returning NotImplemented in the case of a false comparison: True if x is y else NotImplemented. For ne(), by default it delegates to eq() and inverts the result unless it is NotImplemented.

https://docs.python.org/3/reference/datamodel.html

Do not worry is the above line does not make any sense to you. In essence, what the above statement says is,

If they are pointing to different objects we get True, if the 2 names are just different names for the same object we get False.

In other words

Python inverts the result of “==” operator while comparing for non-equality

Alright, too much theory! Time for an example!

Let us see a simple fruit class as shown below.

class fruit():
    def init(self, name, price_kg):
        self.name = name
        self.price_kg = price_kg

The above class has 2 attributes “name” and “price_kg” and a constructor init() to set these attributes.

Let us play with this fruit class by creating some objects on the python interpreter

>>> apple = fruit("apple",10)
>>> mango = fruit("mango",20)
>>> pear = fruit("pear",10)
>>> apple != mango
True
>>> mango != pear
True
>>> apple != pear
True

We have made 3 objects: apple, mango, and pear, with

  • apple and pear being priced at 10 bucks per kg and
  • the mango priced at 20 bucks per kg.

When we do some non-equality checks, all the comparisons between the 3 fruits above result in True.

Let us try creating another apple!

>>> apple2 = fruit("apple", 10)
>>> apple != apple2
True

Even if we made another apple object with the same name and price, we still get True when we try to compare this with the 1st apple!

That is because these 2 apples are different objects stored in 2 different locations in memory!
You can verify this using the built-in id() function.

>>> id(apple)
140610421339424
>>> id(apple2)
140610392624672

Each object is given an ID number when they are created.

As you can see above the objects apple and apple2 has different IDs and hence by default they are “Not Equal”

Okay, so you might be wondering “Does this mean by default every non-equality comparison will result in True?

Let us try to compare apple2 with apple2!

>>> apple2 != apple2
False

Yaay! We got a “False” at last!

But wait for a second, why in the world would we wish to do something like this in our programs anyways!

Okay, that is a valid confusion!

In python, we are allowed to have 2 names for the same object. This is something like a nickname and an official name for the same person.

Since these 2 names refer to the same person, the “names of objects” are also called as “references

Let us see what I mean

>>> apple2_copy = apple2
>>> id(apple2)
140610392624672
>>> id(apple2_copy)
140610392624672
>>> apple2_copy != apple2
False

Here I have created a copy of apple2 called “apple2_copy”. In essence, now we now have 2 names for the same object with id 140610392624672

Now if we do a non-equality comparison, we get False!

So by default the “!=” operator sees if the 2 names being compared are referring to the same object or not!

Internally, to do this, python does something similar to what is shown below with the “!=” operator.

def ne(self, obj)
    if (id(self).ne(id(obj))
        return True
    else
        return False

Let us have another look at the explanation of the default behavior of the “!=” operator.

By default, if they are pointing to different objects we get True, if the 2 names are just different names for the same object we get False.

I hope now you get the meaning behind the lines above and you understand the default behavior of the equality operator perfectly!

Need to change the default behavior of ‘!=’ in user defined classes

Assume we are fruit sellers. When comparing 2 fruits, the only thing fruit sellers are interested in is the parameter “price per kg”.

Let us expand the fruit class by including the ne() method as shown below.

class fruit():
    def init(self, name, price_kg):
        self.name = name
        self.price_kg = price_kg

    def ne(self, b):
        return (self.price_kg != b.price_kg)

Now, the fruit class still has the same 2 attributes “name” and “price_kg” and the init() method a.k.a the constructor. But we have also the ne() method to implement the behavior of the “!=” operator of the fruit class

Fruit selling business

Let us play with this fruit class now in the python interpreter!

>>> peach = fruit("peach", 10)
>>> kiwi = fruit("kiwi", 20)
>>> mango = fruit("mango", 20)
>>> peach != kiwi
True
>>> kiwi == mango
False

As you can see this time, the “!=” operator compares the objects using the price!

Peach and Kiwi have different prices and we get “True“, while Kiwi and mango have the same price and hence we get “False“!

Let us take one more example. Let us take the same fruit class but this time assume we have a shipping business, where we put fruits into crates and ship them.

Fruit shipping business

In this kind of shipping business, we need to know how many fruits can go into one of our crates. Hence we need the size and weight of a given fruit to decide if they are equal or not.

class fruit():
    def init(self, name, diameter, weight):
        self.name = name
        self.diameter = diameter
        self.weight = weight

    def ne(self, b):
        return (self.diameter != b.diameter) or (self.weight != b.weight)

Here we have a class named fruit. Each fruit comes with 3 attributes

  • name,
  • weight and
  • diameter

We have the same 2 methods, the constructor init() and the ne() class which we need to use to compare the fruits for packaging and shipping purposes.

Let us take our new fruit class for a spin!

>>> apple = fruit("apple", 10, 200)
>>> watermelon = fruit("watermelon", 50, 5000)
>>> orange = fruit("orange", 10, 200)
>>> apple != watermelon
True
>>> apple != orange
False
```

As you can see

  • the comparison between apple and watermelon gives us a “True
  • but the comparison between apple and orange gives us a “False“.

That is because, in our class, the ne() operator returns False if the diameter and weight are both equal!

So even though they are not the same fruit, we call them equal as the parameters we care about (the weight and the diameter) are equal. Hence we made the “!=” operator behave exactly the way we wanted it to!

I hope you understood how to define the behavior of the “!=” operator for your own classes!

If you did then bravo! You can successfully mastered the “!=” operator in Python!

Related Operators

There are some more operators in python which act very similar to the “!=” operator in terms of implementation and usage. Since you have already learned everything there is to know about the “!=” operator, you already know everything to know about some more operators too!

These are the 5 other comparison operators like our “!=” operator:

  • > : Greater than
  • >= : Greater than or Equal to
  • < : Less than
  • <= : Less than or Equal to
  • == : Equal to

All these operators are implemented and used very similar to the way we use the “!=” operator.
We have written a separate article explaining each of them using examples, please check them out in the link below!

Python Comparison Operators Explained Using 10 Examples!

“!=” vs “is not” in Python

Other than the comparison operators, there is one more operator which is very similar in behavior to the “!=” operator, which is the “is not” operator.

Let us have a quick look at the difference between the “is not” and the “!=” operator!

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

If the term “references” and “objects” does not sound very familiar to you, please read our article explaining the “is not” operator in great detail, which you can find in the link below.

Python “is not” operator vs “!=” operator

There I have explained in detail

  • the meaning of “references”,
  • how the “is not” operator works and
  • how and when to use “is not” operator as compared to the “!=” operator.

Where to Go from Here

I suggest first playing a bit more with the “!=” operator just to get some practice. Once you are done, the next obvious step would be to go and master the other operators!

You can find the articles in the related articles section below.

If you have made it till the end, then congratulations and keep up this habit of finishing what you start, that is the one habit that differentiates winners from losers, and you have proved yourself to be a winner!

I hope you had some fun reading this article and you learned something useful!
Feel free to share this article with your friends and colleagues!

Related Articles

Here are some of the other articles on our website that you might find interesting!

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

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

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

References

  1. Using the Python Interpreter
  2. Python Data Model

Python "in" and "not in": Explained Using 8 Examples!

Wednesday 24th of November 2021

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

Python's ">" and ">=" Operators: Explained Using 11 Examples

Wednesday 24th of November 2021

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

Python Comparison Operators Explained Using 10 Examples!

Wednesday 24th of November 2021

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

Python “is not” versus “!=”: Explained using 14 Examples!

Wednesday 24th of November 2021

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

Python "is" versus "==": Explained using 11 Examples!

Wednesday 24th of November 2021

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

Comments are closed.