Python in operator

Table of Contents

Introduction

In this post we will see how to use the in and not in operator in Python.

These two statements are used when you want to check whether or not an element is found in a list, tuple or in a string.
More generally they are used to verify the presence of an element within an iterable.

The next sections will explain how to use them and show examples of use.

Python in operator

If you are looking for how to check if an element exists in a group of values, the in operator is the right one!
It can be used with all iterables like lists, tuples and even strings.

The syntax is very simple and the same for all iterables:

<element to search> in <iterable>

The in operator in Python returns True if the element is present in the set of values and False otherwise.

Be careful because this operator is case-sensitive, so “Python” is different from “python”.

Lists

list_of_values = ["python", "c#", "c++", "java"]
print("python" in list_of_values)
print("javascript" in list_of_values)

Output

True
False

Tuples

list_of_values = ("python", "c#", "c++", "java")
print("python" in list_of_values)
print("javascript" in list_of_values)

Output

True
False

Strings

my_string = "python is my favorite programming language"
print("python" in my_string)
print("javascript" in my_string)

Output

True
False

Python not in operator

If you are looking for how to check if an element does NOT exist in a set of values instead, you must use the not in operator.
It can be used with all iterables like lists, tuples and even strings.

The syntax is very simple and the same for all iterables:

<element to search> not in <iterable>

The not in operator in Python returns True if the element is NOT present in the set of values and False otherwise.

Be careful because this operator is case-sensitive, so “Python” is different from “python”.

Lists

list_of_values = ["python", "c#", "c++", "java"]
print("python" not in list_of_values)
print("javascript" not in list_of_values)

Output

False
True

Tuples

list_of_values = ("python", "c#", "c++", "java")
print("python" not in list_of_values)
print("javascript" not in list_of_values)

Output

False
True

Strings

my_string = "python is my favorite programming language"
print("python" not in my_string)
print("javascript" not in my_string)

Output

False
True

Conclusion

This post showed you how Python allows you to search lists, tuples and strings for a certain value using the in operator.
It was also made a deepening on the inverse procedure, that is how to check if an element is not in a group of values using the operator not in.

I hope this post was useful to you and I invite you to ask in the comments below if you have any doubts or if you are in trouble.

Leave a Comment

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