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
What is "not in" operator in Python?
In Python, the not in membership operator evaluates to True if it does not find a variable in the specified sequence and False otherwise.
Syntax
element not in sequence
Example with Lists
Let's check if elements are not present in a list ?
a = 10 b = 4 numbers = [1, 2, 3, 4, 5] print(a not in numbers) print(b not in numbers)
True False
Since a (10) doesn't belong to numbers, a not in numbers returns True. However, b (4) can be found in numbers, hence b not in numbers returns False.
Example with Strings
The not in operator also works with strings to check for substrings ?
text = "Hello World"
print("Python" not in text)
print("Hello" not in text)
print("xyz" not in text)
True False True
Example with Tuples and Sets
You can use not in with any iterable sequence ?
colors_tuple = ("red", "green", "blue")
colors_set = {"red", "green", "blue"}
print("yellow" not in colors_tuple)
print("red" not in colors_set)
print("purple" not in colors_set)
True False True
Comparison with 'in' Operator
| Operator | Returns True When | Example |
|---|---|---|
in |
Element is found |
4 in [1,2,3,4] ? True
|
not in |
Element is not found |
5 not in [1,2,3,4] ? True
|
Conclusion
The not in operator is the logical opposite of in, returning True when an element is absent from a sequence. It works with lists, strings, tuples, sets, and other iterable objects.
Advertisements
