In the Python programming language, various operators are used to accomplish multiple operations. Some of the fundamental operators in Python are “Arithmetic Operators”, “Logical Operators”, “Identity Operators”, etc. The “in” and “not in” operators are binary operators used to perform special operations on values.
In this blog post, we will explain the “in” and “not in” operators using appropriate examples. The following contents will be explored in this post:
How to Use “in” Operator in Python?
The “in” operator checks whether the specified value exists in the given iterable. The below code shows the demonstration of the “in” operator with different data structures of Python:
Code:
list_value= [2, 15, 20, 25, 15]
print(15 in list_value)
string_value= "Python Guide By itslinuxfoss"
print("Java" in string_value)
tuple_value=('Joseph','Henry','Alex')
print('Alex' in tuple_value)
dict_value = {'Name': "ALex", 'Age': 43}
print("Name" in dict_value)
In the above code:
- The list, string, tuple, and dictionary value are initialized in the program.
- The “in” operator is utilized in a program to check whether the particular value exists in the iterator or not.
- If the value is present, the “in” operator returns the boolean “True”. If the value is not present in the targeted iterator, the “in” operator returns the boolean “False”.
Output:
The above code shows the values “True” or “False” according to the “in” operator condition.
How to Use Python “not in” Operators?
When checking whether a particular value is present in the program, the “not in” operator is used in Python. Here is an example of code:
Code:
list_value= [2, 15, 20, 25, 15]
print(15 not in list_value)
string_value= "Python Guide By itslinuxfoss"
print("Java" not in string_value)
tuple_value=('Joseph','Henry','Alex')
print('Alex' not in tuple_value)
dict_value = {'Name': "ALex", 'Age': 43}
print("Name" not in dict_value)
In the above code:
- The list, string, tuple, and dictionary value are initialized.
- The “not in” operator is utilized to check whether the given value appeared in sequence or not.
- If the value is not present, the “not in” operator returns the “True” value, and if the given value is present in the sequence, the “not-in” operator returns the “False” value.
Output:
The “not-in” operator returns the “True” value when the given value does not appear in the sequence.
Conclusion
The “in” operator is utilized to check whether the given value exists in the sequence, and the “not-in” operator checks whether the given value does not exist. The “in” and “not-in” operator returns the boolean value “True” and “False” according to the specified condition. If the condition specified in the “in” or “not-in” operator is satisfied, the “True” value is returned in the output, otherwise false. This Python tutorial proposed a detailed guide on using the “in” and “not in” operators via various examples.