The Wayback Machine - https://web.archive.org/web/20240921152437/https://www.geeksforgeeks.org/python-not-equal-operator/
Open In App

Python NOT EQUAL operator

Last Updated : 14 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we are going to see != (Not equal) operators. In Python,  != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. 

Python NOT EQUAL operators Syntax

The Operator not equal in the Python description:

  • != Not Equal operator, works in both Python 2 and Python 3.
  • <> Not equal operator in Python 2, deprecated in Python 3.

Syntax: Value A != Value B

Return Type:

  • Returns either True or False 

Note: It is important to keep in mind that this comparison operator will return True if the values are the same but are of different data types.

Examples of NOT EQUAL Operator in Python

Here are a few examples of Python NOT EQUAL operators.

Example 1: NOT EQUAL Operator with same DataType

In this example, we are comparing different values of the same datatype, that is integers to see how all values are does not equal Python and how the NOT EQUAL operator works.

Python3




A = 1
B = 2
C = 2
 
print(A!=B)
print(B!=C)


Output:

True
False

Example 2: NOT EQUAL operator with different DataTypes

In this example, we are comparing similar values of the different datatypes to see how the NOT EQUAL operator works. We are taking an integer, a float, and a Python String as input.

Python3




A = 1
B = 1.0
C = "1"
 
print(A!=B)
print(B!=C)
print(A!=C)


Output:

False
True
True

Compare lists in Python using the Not Equal Operator

Python NOT EQUAL operator can also be used to compare two lists. Let’s see how can this be done.

In this example, we are taking 3 Python lists, out of which two are integers and one is a string list. Then we compared them using the does not equal operator in Python.

Python3




list1 = [10, 20, 30]
list2 = [10, 20, 30]
list3 = ["geeks", "for", "geeks"]
 
print(list1 != list2)
print(list1 != list3)


Output:

False
True

Use of if statement with the Not Equal  operator in Python

The NOT EQUAL operator can also be used with the Python if else statements. Let us see a simple example of this.

In this example, we are comparing two strings and then printing a message based on the output of does not equal operator in Python.

Python3




str1 = 'Geeks'
str2 = 'GeeksforGeeks'
 
if str1 != str2:
    print("Strings are not Equal")
else:
    print("Strings are Equal")


Output:

Numbers are not Equal

Python NOT EQUAL Operator with Custom Object

We can also use the NOT EQUAL operator with custom objects in Python. Here is an example of how the does not equal Python operator works with custom objects.

The Python __ne__() decorator gets called whenever the does not equal Python operator in Python is used. We can override this function to alter the nature of the ‘not equal’ operator.

Python3




class Student:
 
    def __init__(self, name):
        self.student_name = name
 
    def __ne__(self, x):
        # return true for different types
        # of object
        if type(x) != type(self):
            return True
           
        # return True for different values
        if self.student_name != x.student_name:
            return True
        else:
            return False
 
s1 = Student("Shyam")
s2 = Student("Raju")
s3 = Student("babu rao")
 
print(s1 != s2)
print(s2 != s3)


Output:

True
True


Previous Article
Next Article

Similar Reads

Check if a value exists in a DataFrame using in &amp; not in operator in Python-Pandas
In this article, Let’s discuss how to check if a given value exists in the dataframe or not.Method 1 : Use in operator to check if an element exists in dataframe. C/C++ Code # import pandas library import pandas as pd # dictionary with list object in values details = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age
3 min read
Difference between != and is not operator in Python
In this article, we are going to see != (Not equal) operators. In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. Whereas is not operator checks whether id() of two objects is same or not. If same, it returns False and if not same, it returns
3 min read
not Operator in Python | Boolean Logic
Python not keyword is a logical operator that is usually used to figure out the negation or opposite boolean value of the operand. The Keyword 'not' is a unary type operator which means that it takes only one operand for the logical operation and returns the complementary of the boolean value of the operand. For example, if we give false as an oper
5 min read
How to Fix "Could Not Identify an Equality Operator for Type Python JSON"?
When working with JSON data in programming languages like JavaScript or TypeScript we might encounter an error message stating "Could Not Identify an Equality Operator for Type JSON." This error occurs because the JSON objects are not natively comparable using equality operators like == or === in many programming languages. Problem StatementConside
5 min read
Python IF with NOT Operator
We can use if with logical not operator in Python. The main use of the logical not operator is that it is used to inverse the value. With the help of not operator, we can convert true value to false and vice versa. When not applied to the value so it reverses it and then the final value is evaluated by the if condition. So according to its final va
6 min read
PostgreSQL - NOT IN operator
The PostgreSQL NOT IN operator works exactly opposite to the IN operator. It is used to filter query results by excluding the specified values from a list. This powerful operator can help simplify your database queries by efficiently excluding unwanted data. Let us better understand the PostgreSQL NOT IN operator from this article. What is the NOT
3 min read
Why 0.3 - 0.2 is not equal to 0.1 in Python?
In this article, we will see why 0.3 - 0.2 is not equal to 0.1 in Python. The reason behind it is called “precision”, and it’s due to the fact that computers do not compute in Decimal, but in Binary. Computers do not use a base 10 system, they use a base 2 system (also called Binary code). Below is the Implementation. C/C++ Code # code print(0.3 -
2 min read
How to do a not equal in Django queryset
In Django, filtering data from the database is typically done through QuerySet methods provided by Django’s ORM (Object Relational Mapping). When you need to filter records where a certain field is not equal to a specific value, Django offers an elegant way to handle this using the exclude() method or the __ne field lookup. This article will guide
4 min read
Difference between == and is operator in Python
When comparing objects in Python, the identity operator is frequently used in contexts where the equality operator == should be. In reality, it is almost never a good idea to use it when comparing data. What is == Operator?To compare objects based on their values, Python's equality operators (==) are employed. It calls the left object's __eq__() cl
3 min read
Python | Operator.countOf
Operator.countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. Syntax : Operator.countOf(freq = a, value = b) Parameters : freq : It can be list or any other data type which store value value : It is value for which we have to count the number of occurrences Returns: Count of number of occ
2 min read
Python | List comprehension vs * operator
* operator and range() in python 3.x has many uses. One of them is to initialize the list. Code : Initializing 1D-list list in Python # Python code to initialize 1D-list # Initialize using star operator # list of size 5 will be initialized. # star is used outside the list. list1 = [0]*5 # Initialize using list comprehension # list of size 5 will be
2 min read
Concatenate two strings using Operator Overloading in Python
Operator Overloading refers to using the same operator to perform different tasks by passing different types of data as arguments. To understand how '+' operator works in two different ways in python let us take the following example C/C++ Code # taking two numbers a = 2 b = 3 # using '+' operator add them c = a+b # printing the result print(&quot;
2 min read
What does the Double Star operator mean in Python?
Double Star or (**) is one of the Arithmetic Operator (Like +, -, *, **, /, //, %) in Python Language. It is also known as Power Operator. What is the Precedence of Arithmetic Operators? Arithmetic operators follow the same precedence rules as in mathematics, and they are: exponential is performed first, multiplication and division are performed ne
3 min read
Create multiple copies of a string in Python by using multiplication operator
In this article, we will see how to create multiple copies of a string by using the multiplication operator(*). Python supports certain operations to be performed on a string, multiplication operator is one of them. Method 1: Simply using multiplication operator on the string to be copied with the required number of times it should be copied. Synta
3 min read
Python MySQL - LIKE() operator
In this article, we will discuss the use of LIKE operator in MySQL using Python language. Sometimes we may require tuples from the database which match certain patterns. For example, we may wish to retrieve all columns where the tuples start with the letter ‘y’, or start with ‘b’ and end with ‘l’, or even more complicated and restrictive string pat
3 min read
Python MySQL - BETWEEN and IN Operator
In this article, we are going to see the database operations BETWEEN and IN operators in MySQL using Python. Both of these operators are used with the WHERE query to check if an expression is within a range or in a list of values in SQL. We are going to use the below table to perform various operations: The SQL BETWEEN condition is used to test if
3 min read
How to use the IN operator in SQLAlchemy in Python?
In this article, we will see how to use the IN operator using SQLAlchemy in Python. We will cover 2 examples, one each for SQLAchemy Core and ORM layers. In both examples, we will count the number of records present in the category table within the sakila database. The sample data from the table looks like. If you do not have sakila database and wa
4 min read
Walrus Operator in Python 3.8
The Walrus Operator is a new addition to Python 3.8 and higher. In this article, we're going to discuss the Walrus operator and explain it with an example. Introduction Walrus Operator allows you to assign a value to a variable within an expression. This can be useful when you need to use a value multiple times in a loop, but don't want to repeat t
2 min read
Difference between / vs. // operator in Python
In this article, we will see the difference between the / vs // operator in Python Python Division OperatorThe division operator '/ ' performs standard division, which can result in a floating-point number. However, if both the dividend and divisor are integers, Python will perform integer division only if the result is an integer. Otherwise, it wi
2 min read
Operator Functions in Python | Set 1
Python has predefined functions for many mathematical, logical, relational, bitwise etc operations under the module "operator". Some of the basic functions are covered in this article. 1. add(a, b) :- This function returns addition of the given arguments. Operation - a + b. 2. sub(a, b) :- This function returns difference of the given arguments. Op
5 min read
Operator Functions in Python | Set 2
Operator Functions in Python | Set 1 More functions are discussed in this article. 1. setitem(ob, pos, val) :- This function is used to assign the value at a particular position in the container. Operation - ob[pos] = val 2. delitem(ob, pos) :- This function is used to delete the value at a particular position in the container. Operation - del ob[p
5 min read
Python - Star or Asterisk operator ( * )
There are a many places you’ll see * and ** used in Python. Many Python Programmers even at the intermediate level are often puzzled when it comes to the asterisk ( * ) character in Python. After studying this article, you will have a solid understanding of the asterisk ( * ) operator in Python and become a better coder in the process! Below are th
3 min read
Ternary Operator in Python
In Python, Ternary Operator determines if a condition is true or false and then returns the appropriate value as the result. The ternary operator is useful in cases where we need to assign a value to a variable based on a simple condition, and we want to keep our code more concise — all in just one line of code. It's convenient when we want to avoi
7 min read
Modulo operator (%) in Python
When we see a '%' the first thing that comes to our mind is the "percent" but in computer language, it means modulo operation(%) which returns the remainder of dividing the left-hand operand by right-hand operand or in layman's terms it finds the remainder or signed remainder after the division of one number by another. Given two positive numbers,
4 min read
Operator Overloading in Python
Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed that the same built-in operator or function shows d
9 min read
Python OR Operator
Python OR Operator takes at least two boolean expressions and returns True if any one of the expressions is True. If all the expressions are False then it returns False. Flowchart of Python OR OperatorTruth Table for Python OR OperatorExpression 1Expression 2ResultTrueTrueTrueTrueFalseTrueFalseTrueTrueFalseFalseFalseUsing Python OR Operator with Bo
4 min read
Operator.length_hint() method in Python
length_hint() method is part of the operator module, which contains a collection of functions that correspond to standard operations and can be useful for functional programming and optimization. How operator.length_hint() WorksThe length_hint() function is designed to interact with objects that implement the __length_hint__ method. This method is
2 min read
New '=' Operator in Python3.8 f-string
Python have introduced the new = operator in f-string for self documenting the strings in Python 3.8.2 version. Now with the help of this expression we can specify names in the string to get the exact value in the strings despite the position of the variable. Now f-string can be defined as f'{expr=}' expression. We can specify any required name in
1 min read
PostgreSQL - IN Operator
The PostgreSQL IN operator is a powerful tool used in conjunction with the WHERE clause to filter records based on a list of values. This operator simplifies queries and enhances readability, making it an essential component of SQL for database manipulation and data retrieval. Let us get a better understanding of the IN operator in PostgreSQL from
3 min read
PostgreSQL - EXISTS Operator
The EXISTS operator in PostgreSQL is a powerful tool for testing the existence of rows in a subquery. This operator is commonly used with correlated subqueries, providing a way to perform efficient existence checks. If the subquery returns at least one row, the result EXISTS is true; otherwise, it is false. Let us get a better understanding of the
3 min read
Practice Tags :