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
What is Python equivalent of the ! operator?
In some languages like C / C++, the "!" symbol is used as a logical NOT operator. !x returns true if x is false, else returns false. The equivalent of this "!" operator in Python is the not keyword, which also returns True if the operand is false and vice versa.
Basic Usage with Boolean Values
Example with True Value
In the following example, the variable operand_X holds a boolean value True. After applying the not operator, it returns False −
operand_X = True
print("Input: ", operand_X)
result = not operand_X
print('Result: ', result)
Input: True Result: False
Example with False Value
For a False value, the not operator returns True −
operand_X = False
print("Input: ", operand_X)
result = not operand_X
print('Result: ', result)
Input: False Result: True
Using not with Different Data Types
String Example
In Python, non-empty strings are considered True. The not operator returns False for non-empty strings −
X = "python"
print("Input: ", X)
result = not X
print('Result: ', result)
Input: python Result: False
Empty List Example
Empty lists are treated as False in Python. Due to this, the not operator returns True for empty list objects −
li = []
print("Input: ", li)
result = not li
print('Result: ', result)
Input: [] Result: True
Using not with Comparison Expressions
The not operator can also be applied to comparison expressions −
print("not(10 < 20): ", not(10 < 20))
print("not(10 > 20): ", not(10 > 20))
print("not(True == True): ", not(True == True))
not(10 < 20): False not(10 > 20): True not(True == True): False
Truthiness in Python
Python considers the following values as False: False, 0, "" (empty string), [] (empty list), {} (empty dict), and None. All other values are considered True.
# Examples of falsy values
print("not 0:", not 0)
print("not '':", not "")
print("not None:", not None)
# Examples of truthy values
print("not 5:", not 5)
print("not 'hello':", not "hello")
print("not [1, 2]:", not [1, 2])
not 0: True not '': True not None: True not 5: False not 'hello': False not [1, 2]: False
Conclusion
The Python not operator is equivalent to the ! operator in C/C++. It returns the opposite boolean value of its operand and works with Python's truthiness concept, making it useful for testing empty collections, None values, and boolean expressions.
