Hit enter after type your search item

How to use Python not equal and equal to operators?

In Python, you may use the equal to (==) and not equal to (!=) operators for testing the equality of two objects.

Examples with code

Not equal (!=) example  equal to (==) example

Python supports a number of comparison operators as given below:

  • ==  Equal to
  • !=  Not equal to
  • >  Greater than
  • >= Greater than or equal to
  • <  Less than
  • <=  Less than or equal to

For example:

Not equal to

int_x != int_y

Equal to:

x == 4

str = ‘Python’

Note: The <> (not equal to or equivalent of !=) was also supported in version 2 of Python, however, this is deprecated in version 3 and produces “Invalid Syntax” Error.

In the following section, I will show you examples of how to use the Python not equal and equal to operator (as the title of this article suggests).

A simple example of not equal operator

For this example, the int_x variable is assigned the value of 20 and int_y = 30. In the if statement, the condition is to check if int_x is not equal to int_y i.e.

Int_x != int_y

If int_x is not equal to int_y then if statement should be True, so statement inside the if block should execute, otherwise, else part should:

See online demo and code


Python not equal

As values of both objects are not equal so condition became True.

Comparison of string object example

In the following example, a string object is created and compared by using the != (not equal to) operator in the if statement.

See online demo and code


not equal to

A demo of equal to (==) operator with while loop

In this example, the Python equal to operator (==) is used in the if statement. A range of values from 2000 to 2030 is created. This is followed by using a for loop to iterate through that range.

The purpose is to get the leap years from 2000 to 2030 and omit all other years from displaying. For that, the if statement is used and the current item in the range is divided by 4. If it is equal to 0, then if the condition becomes True and print function will display the year. Otherwise, the current item is omitted by using the continue statement.

See how equal to (==) operator is used:

See online demo and code


Python equal to

An example of getting even numbers by using not equal operator

For this example, a while loop is used and in the if statement not equal to (!=) operator is used to get the even numbers. Have a look:

See online demo and code


not equal even

You can see, in the while loop, the less than or equal to operator (<=) is also used.

This div height required for enabling the sticky sidebar