Skip to content

In Python: How to Use 'in' Effortlessly!

CodeMDD.io

Python’s “in” and “not in” Operators: Check for Membership

Python’s in and not in operators allow you to quickly determine if a given value is or isn’t part of a collection of values. This type of check is common in programming, and it’s generally known as a membership test in Python. Therefore, these operators are known as membership operators.

Getting Started With Membership Tests in Python

Sometimes you need to find out whether a value is present in a collection of values or not. In other words, you need to check if a given value is or is not a member of a collection of values. This kind of check is commonly known as a membership test.

Arguably, the natural way to perform this kind of check is to iterate over the values and compare them with the target value. You can do this with the help of a for loop and a conditional statement.

Consider the following is_member() function:

def is_member(value, iterable):
for item in iterable:
if value is item or value == item:
return True
return False

This function takes two arguments, the target value and a collection of values, which is generically called iterable. The loop iterates over iterable while the conditional statement checks if the target value is equal to the current value. Note that the condition checks for object identity with is or for value equality with the equality operator (==).

This approach works, but Python provides a more concise and efficient way to perform membership tests using the in and not in operators.

Python’s in Operator

The in operator is used to check if a value is present in a collection. It returns True if the value is found and False otherwise. Here’s an example:

my_list = [1, 2, 3, 4, 5]
# Check if 3 is in my_list
if 3 in my_list:
print("3 is in the list")
else:
print("3 is not in the list")

Output:

3 is in the list

In this example, the in operator checks if the value 3 is present in the my_list list. Since it is, the if statement evaluates to True and the corresponding message is printed. If the value were not present in the list, the if statement would evaluate to False and the corresponding message would be printed.

Python’s not in Operator

The not in operator is used to check if a value is not present in a collection. It returns True if the value is not found and False otherwise. Here’s an example:

my_tuple = (1, 2, 3, 4, 5)
# Check if 6 is not in my_tuple
if 6 not in my_tuple:
print("6 is not in the tuple")
else:
print("6 is in the tuple")

Output:

6 is not in the tuple

In this example, the not in operator checks if the value 6 is not present in the my_tuple tuple. Since it is not, the if statement evaluates to True and the corresponding message is printed. If the value were present in the tuple, the if statement would evaluate to False and the corresponding message would be printed.

Using in and not in With Different Python Types

The in and not in operators can be used with different data types in Python. Let’s explore how they work with some common data types:

Lists, Tuples, and Ranges

The in and not in operators work naturally with lists, tuples, and ranges. Here are some examples:

my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3, 4, 5)
my_range = range(1, 6)
print(3 in my_list) # Output: True
print(6 not in my_tuple) # Output: True
print(1 in my_range) # Output: True
print(7 not in my_list) # Output: True

In these examples, the in and not in operators are used to check if specific values are present or not in the given collections.

Strings

The in and not in operators also work with strings. They allow you to check if a substring is present in a larger string. Here’s an example:

my_string = "Hello, World!"
if "Hello" in my_string:
print("Substring found")
else:
print("Substring not found")

Output:

Substring found

In this example, the in operator is used to check if the substring “Hello” is present in the my_string string. Since it is, the if statement evaluates to True and the corresponding message is printed.

Generators

Generators are a type of iterable in Python. The in and not in operators can be used with generators, just like with other iterables. Here’s an example:

my_generator = (x ** 2 for x in range(1, 6))
if 16 in my_generator:
print("Value found")
else:
print("Value not found")

Output:

Value found

In this example, the in operator is used to check if the value 16 is present in the my_generator generator. Since it is, the if statement evaluates to True and the corresponding message is printed.

Dictionaries and Sets

The in and not in operators also work with dictionaries and sets, but they check for membership in the keys rather than in the values. Here’s an example:

my_dict = {"apple": 1, "banana": 2, "cherry": 3}
my_set = {1, 2, 3}
print("apple" in my_dict) # Output: True
print(4 not in my_set) # Output: True

In these examples, the in and not in operators are used with dictionaries and sets to check if specific keys or values are present or not.

Putting Python’s in and not in Operators Into Action

The in and not in operators are powerful tools that can make your code more concise and efficient. Here are some practical examples of how you can use them:

Replacing Chained or Operators

When you have multiple values to check for, you can use chained or operators (value == item1 or value == item2 or value == item3) to perform membership tests. However, this can become verbose and harder to read as the number of items increases. The in operator provides a more concise alternative. Here’s an example:

my_list = [1, 2, 3, 4, 5]
# Using chained or operators
if value == 1 or value == 2 or value == 3:
print("Value found")
else:
print("Value not found")
# Using the in operator
if value in my_list:
print("Value found")
else:
print("Value not found")

In this example, the first if statement uses chained or operators to check if the value is equal to any of the specified items. The second if statement uses the in operator to check if the value is present in the my_list list. Both approaches yield the same result, but the second one is more concise and easier to read.

Writing Efficient Membership Tests

The in and not in operators can also be used to write more efficient membership tests. Consider the following example:

my_list = [1, 2, 3, 4, 5]
if value in my_list:
print("Value found")

In this example, the in operator checks if the value is present in the my_list list. If the list is long, this membership test can be more efficient than using the is_member() function described earlier.

Using operator.contains() for Membership Tests

In addition to the in operator, Python provides the operator.contains() function, which can be used to perform membership tests. Here’s an example:

import operator
my_list = [1, 2, 3, 4, 5]
if operator.contains(my_list, value):
print("Value found")

In this example, the operator.contains() function is used to check if the value is present in the my_list list. The result is the same as using the in operator.

Supporting Membership Tests in User-Defined Classes

You can also provide support for membership tests in your own classes by implementing the __contains__() special method. This allows instances of your class to be used with the in and not in operators. Here’s an example:

class MyClass:
def __init__(self, items):
self.items = items
def __contains__(self, value):
return value in self.items
my_obj = MyClass([1, 2, 3, 4, 5])
if 3 in my_obj:
print("Value found")

In this example, the MyClass class implements the __contains__() method, which allows instances of the class to work with the in operator. The __contains__() method checks if the specified value is present in the items attribute of the object.

Conclusion

Python’s in and not in operators are powerful tools for performing membership tests. They allow you to quickly and efficiently determine if a value is or isn’t part of a collection of values. Whether you’re working with lists, tuples, strings, generators, dictionaries, or sets, these operators provide a concise and readable way to perform membership tests in Python. Additionally, you can use the operator.contains() function to achieve the same result as the in operator, and you can provide support for membership tests in your own classes by implementing the __contains__() special method. By understanding and using these operators effectively, you can enhance the functionality and readability of your Python code.