Skip to content

Python if not in

  • by

In Python, the if not in statement is not a valid syntax. The correct usage is the not in operator within an if statement. The not in operator is used to check if a value is not present in a sequence.

Here’s the correct syntax for using not in within an if statement in Python:

value = 10
sequence = [1, 2, 3, 4, 5]

if value not in sequence:
    # Code to be executed if value is not present in the sequence
else:
    # Code to be executed if value is present in the sequence

In this example, the not in operator checks if the value 10 is not present in the list sequence. If the value is not found, the condition evaluates to True, and the corresponding block of code is executed.

Remember, not in is an operator used within an if statement to perform a check for absence in a sequence.

Python if not in the example

Here’s an example that demonstrates the usage of the not in operator in Python:

The not in operator is used to check if a value is not present in a sequence (such as a string, list, tuple, or set). It returns a Boolean value (True or False) indicating whether the value is absent.

value = 10
sequence = [1, 2, 3, 4, 5]

if value not in sequence:
    print("Value is not present in the sequence")
else:
    print("Value is present in the sequence")

Output:

Python if not in

Another example using the not in operator with a string:

text = "Hello, World!"

if "Python" not in text:
    print("The word 'Python' is not present in the text.")
else:
    print("The word 'Python' is present in the text.")

Check if something is (not) in a list in Python

To check if an item is present or not present in a list in Python, you can use the in and not in operators within an if statement.

my_list = [1, 2, 3, 4, 5]
value = 3

if value in my_list:
    print("Value is present in the list.")
else:
    print("Value is not present in the list.")

If you want to check if the value is not present in the list, you can use the not in operator:

my_list = [1, 2, 3, 4, 5]
value = 10

if value not in my_list:
    print("Value is not present in the list.")
else:
    print("Value is present in the list.")

You can replace my_list with any list, and value with the item you want to check for presence or absence within the list.

Do comment if you have any doubts or suggestions on this Python if statement topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *