The Wayback Machine - https://web.archive.org/web/20241005214905/https://www.geeksforgeeks.org/python-not-keyword/
Open In App

not Operator in Python | Boolean Logic

Last Updated : 20 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python not keyword is a logical operator that is usually used to figure out the negation or opposite boolean value of the operand. The Keyword ‘not’ is a unary type operator which means that it takes only one operand for the logical operation and returns the complementary of the boolean value of the operand. For example, if we give false as an operand to the not keyword we get true as the return value. 

Syntax: not var

How to Use Not Operator in Python?

The not operator is very easy to use. You just need to use the ‘not’ keyword in front of the variable. Let’s understand it better with an example:

Example: Basic example of not operator with true variable.

Python3




a = True
print(not a)


Output:

False

As you can see from the above example, we just used not operator to change the true value to false.

Practical Applications

The possible practical applications of the ‘not’ keyword are: 

  1. This keyword is mostly used for altering the boolean value.
  2. It is used with an if statement. It is used to negate the condition in the if statement, 
  3. 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 the collection of data.

More Examples on Not Operator

Let’s look at some examples of not operator in Python codes, each example shows different use-cases of not operator.

Python not operator with Variable

Basic example of not operator with variable.

Python3




# variable
a = False
print(not a)


Output:

True

Using the “not” Boolean Operator in Python with Specific condition

As basic property of the ‘not’ keyword is that it is used to invert the truth value of the operand. So we can see here that the result of every value is inverted from their true value. At #5 we can see the compare operation result would be false, so by negation of it we get the True value. Similarly, we can see all results are inverted.

Python3




# Python code to demonstrate
# 'not' keyword
 
# Function showing working of not keyword
def geek_Func():
   
    # 1 Not with False boolean value
    geek_x = not False
    print('Negation  of False : ', geek_x)
 
    # 2 Not with true boolean value
    geek_y = not True
    print('Negation of True : ', geek_y)
 
    # 3 Not with result of and operation
    geek_and = not(True and False)
    print('Negation of result of And operation : ', geek_and)
 
    # 4 Not with result of or operation
    geek_or = not(True or False)
    print('Negation of result of or operation : ', geek_or)
 
    # 5 Not with result of compare operation
    geek_Com = not (5 > 7)
    print('Negation of result of And operation : ', geek_Com)
 
 
geek_Func()


Output: 

Negation  of False :  True
Negation of True :  False
Negation of result of And operation :  True
Negation of result of or operation :  False
Negation of result of And operation :  True

Using the Not Operator with different Value

In this Code, we show the working of the ‘not’ operator with a different value other than boolean, and see how it works. 

Python3




# Python code to demonstrate
# 'not' keyword
 
# Function showing working of not keyword
def geek_Func():
   
    # Not with String boolean value
    geek_Str = "geek"
    print('Negation  of String : ', not geek_Str)
 
    # Not with list boolean value
    geek_List = [1, 2, 3, 4]
    print('Negation of list : ', not geek_List)
 
    # Not with dictionary
    geek_Dict = {"geek": "sam", "collage": "Mit"}
    print('Negation of dictionary : ', not geek_Dict)
 
    # Not with Empty String
    geek_EDict = ""
    print('Negation of Empty String : ', not geek_EDict)
 
    # Not with Empty list
    geek_EList = []
    print('Negation of Empty List : ', not geek_EList)
 
    # Not with Empty dictionary
    geek_EStr = {}
    print('Negation of Empty Dictionary : ', not geek_EStr)
 
geek_Func()


Output: 

Negation  of String :  False
Negation of list :  False
Negation of dictionary :  False
Negation of Empty String :  True
Negation of Empty List :  True
Negation of Empty Dictionary :  True

In the above example, we saw that treating all the data types as operands with not keyword., ‘not’ treats true to all the data types who had value and false to those who were empty value.

Logical NOT operator with the list

Here in this example, we are using Not operator with the list:

Python3




# Python code to demonstrate
# 'not' keyword
 
 
geek_list = [5, 10, 20, 59, 134, 83, 95]
 
# Function showing working of not keyword
def geek_Func():
   
    # Using not with if statement
    if not geek_list:
        print("Inputted list is Empty")
    else:
        for i in geek_list:
            if not(i % 5):
               
                # Using not with in statement
                if i not in (0, 10):
                    print("Multiple is not in range")
                else:
                    print(i)
            else:
                print("The number is not multiple of 5")
 
geek_Func()


Output: 

Multiple is not in range
10
MUltiple is not in range
The number is not multiple of 5
The number is not multiple of 5
The number is not multiple of 5
Multiple is not in range

We have covered the meaning, syntax, and uses of the not operator in Python. This might have given you the complete picture of what is not in Python. You can look at the above examples or experiment on your device about not operator. It is a very basic yet useful operator in Python.

Read More on Python Operator

Similar Reads



Previous Article
Next Article

Similar Reads

Understanding Boolean Logic in Python 3
Booleans are simple and easy to use concepts that exist in every programming language. A boolean represents an idea of "true" or "false." While writing an algorithm or any program, there are often situations where we want to execute different code in different situations. Booleans help our code to do just that easy and effective. More often, a bool
3 min read
Classical NOT logic gates with quantum circuit using Qiskit in Python
In this article, we are going to see how to apply NOT gate on a given input ( 0 or 1 ) using quantum gates, we have to convert 0 to 1 and 1 to 0. This can be done easily in classical computers, but how can we do this in quantum computers. We have to represent the input in qubits and then we apply the X (representation of NOT gate in the quantum com
3 min read
G-Fact 19 (Logical and Bitwise Not Operators on Boolean)
Most of the languages including C, C++, Java, and Python provide a boolean type that can be either set to False or True. In this article, we will see about logical and bitwise not operators on boolean. Logical Not (or !) Operator in PythonIn Python, the logical not operator is used to invert the truth value of a Boolean expression, returning True i
4 min read
Check if a value exists in a DataFrame using in & not in operator in Python-Pandas
In this article, Let’s discuss how to check if a given value exists in the dataframe or not.Method 1 : Use in operator to check if an element exists in dataframe. C/C++ Code # import pandas library import pandas as pd # dictionary with list object in values details = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age
3 min read
Difference between != and is not operator in Python
In this article, we are going to see != (Not equal) operators. In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. Whereas is not operator checks whether id() of two objects is same or not. If same, it returns False and if not same, it returns
3 min read
Python NOT EQUAL operator
In this article, we are going to see != (Not equal) operators. In Python, != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. Python NOT EQUAL operators SyntaxThe Operator not equal in the Python description: != Not Equal operator, works in both Python
3 min read
How to Fix "Could Not Identify an Equality Operator for Type Python JSON"?
When working with JSON data in programming languages like JavaScript or TypeScript we might encounter an error message stating "Could Not Identify an Equality Operator for Type JSON." This error occurs because the JSON objects are not natively comparable using equality operators like == or === in many programming languages. Problem StatementConside
5 min read
Python IF with NOT Operator
We can use if with logical not operator in Python. The main use of the logical not operator is that it is used to inverse the value. With the help of not operator, we can convert true value to false and vice versa. When not applied to the value so it reverses it and then the final value is evaluated by the if condition. So according to its final va
6 min read
Python | Print unique rows in a given boolean matrix using Set with tuples
Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn't matter. Examples: Input: mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] Output: (1, 1, 1, 0, 0) (0, 1, 0, 0, 1) (1, 0, 1, 1, 0) We have existing solution for this problem please refer link. We can solve this problem in python
2 min read
Return a boolean array which is True where the string element in array ends with suffix in Python
In this article, we are going to see how we will return a boolean array which is True where the string element in the array ends with a suffix in Python. numpy.char.endswith() numpy.char.endswith() return True if the elements end with the given substring otherwise it will return False. Syntax : np.char.endswith(input_numpy_array,'substring') Parame
2 min read
Python EasyGUI – Boolean Box
Boolean Box : It is used to display a window having a multiple options i.e buttons in EasyGUI, it can be used where there is a need to get if the first selection option as it returns 1 for button having index 0 and for other button it returns 0, it is slightly different from index box, below is how the boolean box looks like In order to do this we
3 min read
How to invert the elements of a boolean array in Python?
Given a boolean array the task here is to invert its elements. A boolean array is an array which contains only boolean values like True or False, 1 or 0. Input : A=[true , true , false] Output: A= [false , false , true] Input: A=[0,1,0,1] Output: A=[1,0,1,0] Method 1: You can use simple if else method to invert the array. In the implementation show
2 min read
How to parse boolean values with `argparse` in Python
Command-line arguments are a powerful feature of many programming languages, including Python. They allow developers to specify options or parameters when running a script, making it more flexible and customizable. However, the process of parsing these arguments can be a tedious and error-prone task if done manually. The 'argparse' module in Python
5 min read
Python - Boolean Array in NumPy
In this article, I'll be explaining how to generate boolean arrays in NumPy and utilize them in your code. In NumPy, boolean arrays are straightforward NumPy arrays with array components that are either "True" or "False." Note: 0 and None are considered False and everything else is considered True. Examples: Input: arr = [1, 0, 1, 0, 0, 1, 0]Output
3 min read
Python Boolean
Python boolean type is one of the built-in data types provided by Python, which represents one of the two values i.e. True or False. Generally, it is used to represent the truth values of the expressions. Example Input: 1==1Output: True Input: 2<1 Output: FalsePython Boolean TypeThe boolean value can be of two types only i.e. either True or Fals
8 min read
Flipping the boolean values in a Python list
Flipping boolean values in a list involves changing True to False and False to True. This operation is straightforward in Python and can be accomplished using various methods. In this article, we'll explore different techniques to flip boolean values in a list in Python. 1. Using List ComprehensionList comprehension is a concise way to create lists
3 min read
PostgreSQL - NOT IN operator
The PostgreSQL NOT IN operator works exactly opposite to the IN operator. It is used to filter query results by excluding the specified values from a list. This powerful operator can help simplify your database queries by efficiently excluding unwanted data. Let us better understand the PostgreSQL NOT IN operator from this article. What is the NOT
3 min read
Change your way to put logic in your code - Python
Aren't you bored coding in the same traditional logic over these years. It's time to bring some differences. Well, be it any programming language. When we are asked to do some sort of basic programming exercises like sorting, searching, prime number checking, etc. we are all driven towards the same boat, which is the same coding logic. Now, we are
5 min read
Logic Gates in Python
Logic gates are elementary building blocks for any digital circuits. It takes one or two inputs and produces output based on those inputs. Outputs may be high (1) or low (0). Logic gates are implemented using diodes or transistors. It can also be constructed using vacuum tubes, and electromagnetic elements like optics, molecules, etc. In a computer
7 min read
Scala short ==(x: Int): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The ==(x: Int) method is utilized to return true if this value is equal to x, false otherwise. Method Definition: def ==(x: Int): Boolean Return Type: It returns true if this value is equal to x, otherwise false. Example #1: // Scala program of
1 min read
Boolean Operators - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variable
5 min read
Boolean Fields in Serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
4 min read
How to Return a Boolean Array True Where the String Array Ends with Suffix Using NumPy?
In this article, we will discuss how to return a boolean array that is True where the string element in the array ends with a suffix using NumPy in Python. Example: Check the array ends with Com Input: person_1@abc.com Output: True Input: person_3@xyz.co Output: False In Python, numpy.char module provides a set of vectorized string operations for a
2 min read
Boolean Data Type
In programming languages, we have various data types to store different types of data. Some of the most used data types are integer, string, float, and boolean. The boolean data type is a type of data that stores only two types of values i.e. True or False. These values are not case-sensitive depending upon programming languages. The name Boolean c
13 min read
Separation of Business Logic and Data Access in Django
In our Django views, there are two distinct and significant concerns: how we carry out database actions and how we implement business logic in our endpoints. Simple read, create, update, and delete operations similar to those offered by Django's Model layer may or may not be involved in the former. In the data management layer, decisions are made a
6 min read
Difference between == and is operator in Python
When comparing objects in Python, the identity operator is frequently used in contexts where the equality operator == should be. In reality, it is almost never a good idea to use it when comparing data. What is == Operator?To compare objects based on their values, Python's equality operators (==) are employed. It calls the left object's __eq__() cl
3 min read
Python | Operator.countOf
Operator.countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. Syntax : Operator.countOf(freq = a, value = b) Parameters : freq : It can be list or any other data type which store value value : It is value for which we have to count the number of occurrences Returns: Count of number of occ
2 min read
Python | List comprehension vs * operator
* operator and range() in python 3.x has many uses. One of them is to initialize the list. Code : Initializing 1D-list list in Python # Python code to initialize 1D-list # Initialize using star operator # list of size 5 will be initialized. # star is used outside the list. list1 = [0]*5 # Initialize using list comprehension # list of size 5 will be
2 min read
Concatenate two strings using Operator Overloading in Python
Operator Overloading refers to using the same operator to perform different tasks by passing different types of data as arguments. To understand how '+' operator works in two different ways in python let us take the following example C/C++ Code # taking two numbers a = 2 b = 3 # using '+' operator add them c = a+b # printing the result print("
2 min read
What does the Double Star operator mean in Python?
Double Star or (**) is one of the Arithmetic Operator (Like +, -, *, **, /, //, %) in Python Language. It is also known as Power Operator. What is the Precedence of Arithmetic Operators? Arithmetic operators follow the same precedence rules as in mathematics, and they are: exponential is performed first, multiplication and division are performed ne
3 min read
Practice Tags :