What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Not Equal Operator in Python (With Examples)

  • Oct 07, 2023
  • 10 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Nihal Mahansaria
Not Equal Operator in Python (With Examples)

In Python programming, operators play a crucial role in performing various operations on values and variables. One such operator is the not equal operator, which allows us to compare two or more values and determine if they are not equal to each other. In this tutorial, we will explore the not equal operator in Python and learn how to use it effectively in our code.

Operators and Operands in Python

Before diving into the not equal operator, let's first understand the concept of operators and operands in Python. Operators are symbols that represent specific actions or processes, while operands are the values or variables on which these operations are performed.

For example, the addition operator + is used to add the values of two operands:

a = 10
b = 5
result = a + b
print(result)

 

In this example, the addition operator + performs the operation of adding the values of a and b, which are the operands. The result is then stored in the variable result and printed to the console.

Similarly, we have other operators like the multiplication operator *, subtraction operator -, and division operator /, which perform their respective operations on operands.

The Not Equal Operator in Python

The not equal operator (!=) in Python is a comparison operator that compares two or more values and returns 'True' if they are not equal, and 'False' if they are equal. It is denoted by the != symbol.

Let's look at a few examples to see how the not equal operator works:

x = 10
y = 5
print(x != y)

 

In this example, the not equal operator != compares the values of x and y, which are 10 and 5 respectively. Since they are not equal, the expression evaluates to True.

We can also compare strings using the not equal operator:

name1 = "Fav"
name2 = "Tutor"
print(name1 != name2)

 

In this case, the not equal operator compares the values of name1 and name2, which are "Fav" and "Tutor" respectively. Since they are not equal, the expression evaluates to True.

The not equal operator can be used to compare other data types as well, such as lists, dictionaries, tuples, and sets. It allows us to check for inequality between different data elements effectively.

Using the Not Equal Operator with Control Statements in Python

The not equal operator can be particularly useful when used in control statements like if and while loops. These statements allow us to execute certain code blocks based on certain conditions.

Let's see an example of using the not equal operator in an if statement:

age = 18
if age != 21:
    print("You are not allowed to enter the club.")

 

In this example, we use the not equal operator != to compare the value of age with 21. If the value is not equal to 21, the code block inside the if statement is executed, and the message "You are not allowed to enter the club." is printed to the console.

This allows us to control the flow of our program based on certain conditions, giving us the flexibility to handle different scenarios.

Comparing Multiple Values with the Not Equal Operator in Python

The not equal operator can also be used to compare multiple values at once. We can chain multiple not equal operators together to compare different variables or values.

Let's see an example:

x = 10
y = 5
z = 7
if x != y != z:
    print("All three values are not equal.") 

 

In this example, we compare the values of x, y and z using the not equal operator !=. If all three values are not equal, the code block inside the if statement is executed, and the message "All three values are not equal." is printed to the console.

This allows us to perform complex comparisons and make decisions based on multiple conditions.

Combinig the Not Equal Operators with Other Operators in Python

Combining != with == (Not Equal and Equal)

The combination of != (not equal) and == (equal) operators allows you to compare if two values are different or identical. When you use !=, you are checking if two values are not equal. Combining it with == in an if statement allows you to distinguish between equality and inequality.

x = 5
y = 10

if x != y:
   print("x is not equal to y")
else:
   print("x is equal to y")


In this code, we compare the values of x and y. The != operator checks if they are not equal. Since x is not equal to y, the condition is True, and the code inside the if block is executed, resulting in the output "x is not equal to y."

Combining != with < (Not Equal and Less Than)

Combining != with < allows you to check if one value is not equal to another and also less than it. This combination is useful when you want to identify cases where one value is both different and smaller than the other.

a = 7
b = 10

if a != b:
   if a < b:
      print("a is less than b")
   else:
      print("a is greater than b")
else:
   print("a is equal to b")


Here, the code first checks if a is not equal to b. Since that condition is true, it proceeds to check if a is less than b. Since a is indeed less than b, the code inside the first if block is executed, resulting in the output "a is less than b."

Combining != with >= (Not Equal and Greater Than or Equal To)

The combination of != with >= helps you determine if one value is not equal to another and also greater than or equal to it. This is useful when you need to identify cases where one value is both different and greater than or equal to the other.

m = 15
n = 10

if m != n:
   if m >= n:
      print("m is greater than or equal to n")
   else:
      print("m is less than n")
else:
   print("m is equal to n")



In this example, the code first checks if m is not equal to n, which is true. It then proceeds to check if m is greater than or equal to n, which is also true. Therefore, the code inside the first if block is executed, resulting in the output "m is greater than or equal to n."

Combining != with <= (Not Equal and Less Than or Equal To)

Using != along with <= allows you to check if one value is not equal to another and also less than or equal to it. This combination

p = 10
q = 10

if p != q:
   if p <= q:
      print("p is less than or equal to q")
   else:
     print("p is greater than q")
else:
   print("p is equal to q")


In this case, p and q are equal, so the initial if condition p != q is false. As a result, the code goes directly to the else block, which prints "p is equal to q."

These theoretical explanations should help clarify the concepts before diving into the code examples and their detailed explanations.

Common Use Cases for the "Not Equal" Operator in Python

The "Not Equal" operator (!=) in Python is a powerful tool for comparing values and determining inequality. It finds wide application in various scenarios across different types of Python programs. Let's explore some common use cases where you might encounter and utilize the != operator:

Conditional Statements:

One of the most frequent use cases for != is within conditional statements. When you need to execute different blocks of code based on whether two values are not equal, you can employ the != operator. For instance:

user_input = input("Enter a password: ")
if user_input != "secret":
   print("Access denied.")
else:
   print("Access granted.")


In this example, the program checks if the user's input does not match the expected password ("secret") and responds accordingly.

Data Filtering:

When working with data, particularly in data science or data analysis tasks, you might need to filter out specific values that do not meet certain criteria. The != operator is invaluable in such cases. For example:

# Filtering out non-numeric values from a list
numbers = [1, 2, 'three', 4, 'five']
filtered_numbers = [x for x in numbers if type(x) != str]
print(filtered_numbers)


Here, != helps identify and exclude non-numeric values from the list.

Input Validation:

When developing applications that require user input, input validation is crucial to ensure that the provided data meets specific requirements. The != operator can be used to check if user input differs from expected values. For example:

age = int(input("Enter your age: "))
if age < 18 or age > 65:
   print("Sorry, you are not eligible for this program.")
else:
   print("Welcome to our program!")


In this case, != isn't directly used, but the inequality condition is checked to validate user input.

Error Handling:

When handling errors or exceptions in Python, you may want to execute specific code blocks based on the type of error encountered. The != operator can be used to differentiate between different error types. Here's an example:

try:
   result = 10 / 0
except ZeroDivisionError as e:
   if str(e) != "division by zero":
      print("An unexpected error occurred:", str(e))
   else:
      print("You attempted to divide by zero.")


Here, != helps distinguish between a "ZeroDivisionError" and other possible exceptions.

Filtering Lists or Iterables:

In scenarios where you need to filter items from a list or iterable, the != operator can be part of a lambda function or a filter operation. For instance:

# Filtering out specific elements from a list
fruits = ['apple', 'banana', 'cherry', 'date', 'banana']
filtered_fruits = filter(lambda fruit: fruit != 'banana', fruits)
filtered_fruits = list(filtered_fruits)
print(filtered_fruits)

 

Here, != is used to exclude specific elements from the list.

These common use cases demonstrate the versatility and importance of the "Not Equal" operator in Python. It allows you to make decisions, filter data, validate input, handle errors, and perform various other operations effectively in your Python programs. Whether you're building web applications, data analysis tools, or automation scripts, the != operator is a valuable tool in your programming arsenal.

Conclusion

In this tutorial, we explored the not equal operator in Python and learned how to use it effectively in our code. The not equal operator (!=) allows us to compare two or more values and determine if they are not equal. We saw examples of using the not equal operator with different data types and how it can be used in control statements like if statements. By using the not equal operator, we can make our code more flexible and handle different scenarios based on conditions.

If you want to learn more about Python programming, consider exploring the wide range of resources and courses available online. Happy coding!

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Nihal Mahansaria
As a computer science student with a passion for technology and a drive to learn, I have developed a diverse set of skills in web development, machine learning, and technical content writing. With experience in multiple front-end and back-end frameworks, including Flask and Python, I am able to create scalable and efficient web applications.