not Operator in Python
The not keyword in Python is a logical operator used to obtain the negation or opposite Boolean value of an operand.
- It is a unary operator, meaning it takes only one operand and returns its complementary Boolean value.
- For example, if False is given as an operand to not, it returns True and vice versa.
Example: Basic example of not operator with True. Here, we used "not" operator to change the true value to false which is the negation of True.
a = True
print(not a)
Output
False
Practical Applications
The possible practical applications of the "not" keyword are:
- This keyword is mostly used for altering the boolean value.
- It is used with an if statement. It is used to negate the condition in the if statement.
- The "not" keyword is also used with "in keyword". It is used with the "in" keyword when we are searching for a specific value in a collection of data.
Examples of Not Operator
Let's look at some examples of not operator in Python codes, each example shows different use-cases of "not" operator.
Example 1: Python "not" operator with Variables
Basic example of "not" operator with variable.
a = False
print(not a)
Output
True
Explanation: The not operator negates the value of a, turning False into True.
Example 2: Using the "not" Boolean Operator in Python with Specific condition
This example shows various ways to use the not operator with different Boolean values and expressions.
print(not False)
print(not True)_
print(not(True and False))
print(not(True or False))
print(not (5 > 7))
Output
True False True False True
Explanation: The not operator negates each Boolean expression. For example, not True becomes False and not(False and True) becomes True.
Example 3: Using the Not Operator with different Value
This example demonstrates the behavior of the not operator with different data types like strings, lists and dictionaries.
s = "geek"
print(not s)
a = [1, 2, 3, 4]
print(not a)
d = {"geek": "sam", "collage": "Mit"}
print(not d)
es = ""
print(not es)
el = []
print(not el)
ed = {}
print(not ed)
Output
False False False True True True
Explanation: The not operator returns False for non-empty values (strings, lists, dictionaries) and True for empty ones. For example, not "geek" is False and not "" is True.
Example 4: Logical NOT operator with the list
This example uses the not operator in a condition to check the properties of items in a list.
a = [5, 10, 20, 59, 83]
if not a:
print("Inputted list is Empty")
else:
for i in a:
if not(i % 5):
if i not in (0, 10):
print(i,"is not in range")
else:
print(i, "in range")
else:
print(i,"is not multiple of 5")
Output
5 is not in range 10 in range 20 is not in range 59 is not multiple of 5 83 is not multiple of 5
Explanation: The not operator is used to check if the list a is empty or if a number is a multiple of 5. If the list is empty, it prints "Inputted list is Empty". It also checks for numbers not in the range [0, 10].
Related Articles: