Skip to content

How to Use Python Effortlessly

CodeMDD.io

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

Python’s in and not in operators are used to determine if a value is part of a collection of values. This is known as a membership test in Python. In this tutorial, you’ll learn how to perform membership tests using these operators, work with different data types, and use the operator.contains() function. You’ll also learn how to provide support for membership tests in your own classes.

To get started, you’ll need basic knowledge of Python, including built-in data types like lists, tuples, ranges, strings, sets, and dictionaries. It’s also helpful to have knowledge of generators, list comprehensions, and classes.

Getting Started With Membership Tests in Python

When you want to check if a value is present in a collection, you can iterate over the values and compare them to the target value. For example, you can use a for loop and a conditional statement to perform this check. Here’s an example of a function called is_member() that performs a membership test:

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

The is_member() function takes two arguments: the target value and the collection of values, which is referred to as iterable. The function iterates over the iterable and checks if the value is equal to the current item. It returns True if a match is found, and False if no match is found.

Python’s “in” Operator

Python provides a more concise way to perform membership tests using the in operator. The in operator returns True if the value is found in the collection, and False otherwise. Here’s an example:

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

In this example, the in operator is used to check if the value 3 is present in the list numbers. Since 3 is indeed in the list, the output will be “3 is in the list”.

Python’s “not in” Operator

The not in operator is the opposite of the in operator. It returns True if the value is not found in the collection, and False if it is found. Here’s an example:

fruits = ["apple", "banana", "orange"]
if "kiwi" not in fruits:
print("Kiwi is not in the list")
else:
print("Kiwi is in the list")

In this example, the not in operator is used to check if the value "kiwi" is not present in the list fruits. Since "kiwi" is not in the list, the output will be “Kiwi is not in the list”.

Using “in” and “not in” With Different Data Types

You can use the in and not in operators with different data types. Here are some examples:

Lists, Tuples, and Ranges

numbers = [1, 2, 3, 4, 5]
if 3 in numbers:
print("3 is in the list")
letters = ("a", "b", "c", "d")
if "b" in letters:
print("b is in the tuple")
if 5 in range(1, 10):
print("5 is in the range")

In these examples, the in operator is used to check if a value is present in a list, tuple, or range.

Strings

message = "Hello, World!"
if "o" in message:
print("The letter 'o' is in the string")
if "Python" not in message:
print("The word 'Python' is not in the string")

In this example, the in operator is used to check if a letter or word is present in a string.

Generators

def even_numbers():
for i in range(1, 10):
if i % 2 == 0:
yield i
if 4 in even_numbers():
print("4 is an even number")
if 7 not in even_numbers():
print("7 is not an even number")

In this example, the in and not in operators are used to check if a value is present or not in a generator.

Dictionaries and Sets

student_grades = {"Alice": 92, "Bob": 85, "Charlie": 89}
if "Alice" in student_grades:
print("Alice is in the dictionary")
if 85 not in student_grades.values():
print("85 is not in the values of the dictionary")
favorite_numbers = {1, 3, 5, 7, 9}
if 3 in favorite_numbers:
print("3 is in the set")
if 10 not in favorite_numbers:
print("10 is not in the set")

In these examples, the in and not in operators are used to check if a key or value is present in a dictionary, or if a value is present in a set.

Putting Python’s “in” and “not in” Operators Into Action

You can use the in and not in operators in various scenarios. Here are a couple of examples:

Replacing Chained or Operators

languages = ["Python", "Java", "C++"]
if "Python" in languages or "Java" in languages or "C++" in languages:
print("At least one of the languages is in the list")
if any(lang in languages for lang in ["Python", "Java", "C++"]):
print("At least one of the languages is in the list")

In this example, the in operator is used to check if at least one of the languages is present in the list. The first version uses chained or operators, while the second version uses the any() function with a generator expression.

Writing Efficient Membership Tests

numbers = [1, 2, 3, 4, 5]
if set(numbers) & set([3, 4, 5]):
print("At least one number is in the intersection")
if any(number in [3, 4, 5] for number in numbers):
print("At least one number is in the list")

In this example, the in operator is used to check if at least one number is present either in the intersection of two sets or in the list.

Using operator.contains() for Membership Tests

Python’s operator module provides a function called contains() that is equivalent to the in operator. Here’s an example:

import operator
words = ["hello", "world", "python"]
if operator.contains(words, "world"):
print("The word 'world' is in the list")

In this example, the contains() function is used to check if the word "world" is present in the list words.

Supporting Membership Tests in User-Defined Classes

If you want to provide support for membership tests in your own classes, you can define the __contains__() method. Here’s an example:

class Circle:
def __init__(self, radius):
self.radius = radius
def __contains__(self, point):
if isinstance(point, tuple) and len(point) == 2:
x, y = point
distance = (x ** 2 + y ** 2) ** 0.5
if distance <= self.radius:
return True
return False
circle = Circle(5)
if (1, 1) in circle:
print("The point (1, 1) is inside the circle")
if (10, 10) not in circle:
print("The point (10, 10) is outside the circle")

In this example, the Circle class defines the __contains__() method to check if a point is inside the circle. The method accepts a point as an argument and returns True if it is inside the circle, and False otherwise.

Conclusion

Python’s in and not in operators provide a concise way to perform membership tests in Python. You can use them with different data types, including lists, tuples, ranges, strings, generators, dictionaries, and sets. You can also use the operator.contains() function as an alternative to the in operator. Additionally, you can provide support for membership tests in your own classes by defining the __contains__() method.

CodeMDD.io