Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Is there a "not equal" operator in Python?
Python provides the not equal operator to compare values and check if they are different. The != operator is the standard way to perform "not equal" comparisons in modern Python.
The != Operator
The != operator returns True when two values are not equal, and False when they are equal ?
# Comparing numbers
result1 = 5 != 3
result2 = 5 != 5
print("5 != 3:", result1)
print("5 != 5:", result2)
5 != 3: True 5 != 5: False
Using != with Different Data Types
The not equal operator works with strings, lists, and other data types ?
# String comparison
name1 = "Alice"
name2 = "Bob"
print("Alice != Bob:", name1 != name2)
# List comparison
list1 = [1, 2, 3]
list2 = [1, 2, 4]
print("[1,2,3] != [1,2,4]:", list1 != list2)
# Mixed types
print("5 != '5':", 5 != '5')
Alice != Bob: True [1,2,3] != [1,2,4]: True 5 != '5': True
The Deprecated <> Operator
In Python 2, both != and <> operators worked as "not equal". However, <> was removed in Python 3 ?
# Python 2 only (deprecated) # result = 5 <> 3 # This would cause SyntaxError in Python 3 # Modern Python 3 approach result = 5 != 3 print(result)
Practical Example
Here's how to use the not equal operator in conditional statements ?
user_input = "hello"
expected = "world"
if user_input != expected:
print("Input does not match expected value")
else:
print("Input matches expected value")
# Checking multiple conditions
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num != 3:
print(f"{num} is not equal to 3")
Input does not match expected value 1 is not equal to 3 2 is not equal to 3 4 is not equal to 3 5 is not equal to 3
Comparison with Other Operators
| Operator | Description | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 5 != 3 |
True |
<> |
Not equal (deprecated) | Python 2 only | Removed in Python 3 |
Conclusion
Use != as the standard "not equal" operator in Python. The <> operator was deprecated in Python 3, so always use != for modern Python code.
Advertisements
