
Python Boolean Operators "in" and "not in" - Interactive Tutorial
Table of content
Getting started with membership tests
Using the 'in' operator
Using the 'not in' operator
Using 'in' and 'not in' with different Python types
Concrete examples of using the 'in' and 'not in' operators
Replacing chained 'or' operators
Writing efficient membership tests
Using 'operator.contains()' for membership tests
Support for membership tests in user-defined classes
Conclusion
Share with
Getting started with membership tests
in and not in, are powerful tools for checking if an element is present in a data structure, such as a list, tuple, or dictionary. Let's start by exploring how these operators work and how to use them effectively.Basic usage of in and not in
in operator is used to check if an element exists in a sequence. For example, let's say we have a list of fruits:not in:Membership operators with strings
in checks if the substring 'mour' is present in the phrase string.Advanced use cases
in and not in only check for the presence of keys and not values:Performance of membership tests
set) or a dictionary is generally faster than in a list, due to how these data structures are implemented in Python.in and not in operators in Python is not only intuitive but also essential for writing efficient and readable code. These operators allow for quick checks and are fundamental elements for anyone working with data collections in Python.Using the 'in' operator
in operator is a versatile tool that can be used in various contexts in Python. In this section, we will explore some of the most common and useful applications of this operator.Checking in lists
in operator. Here’s a simple example:Using with iterables
in operator works not only with lists but also with any iterable, including tuples and sets:in to be used in a variety of contexts, making the code more adaptable and easier to maintain.Application in dictionaries
in is used to check for the presence of keys in a dictionary. However, it can also be used in combination with methods like .values() and .items() to check for the presence of values or key-value pairs:Loops and conditions
in operator is often used in for loops to iterate over elements:in is commonly used in conditions to make decisions based on the presence of elements.in operator is essential for writing concise and efficient Python code. Whether for membership checks, iterating over collections, or interacting with complex data structures, in is an indispensable tool for any Python developer.Using the 'not in' operator
not in operator is the logical complement of in and is used to check for the absence of an element in a sequence or data structure. This check is often necessary in many programming scenarios to ensure that an element is not present in a collection before proceeding with a specific operation.Avoiding duplicates
not in is to prevent the insertion of duplicates in a list:not in ensures that new_number is added to numbers only if it is not already present.Input validation
not in is also used in input validation to ensure that incorrect or undesirable data is not processed:Error handling
not in can help avoid errors by ensuring that certain conditions are met before executing an operation:Using in loops
not in can also be used in loops to filter elements:not in is used to skip certain elements during iteration, which is handy for applying filters or specific conditions.not in operator is a powerful tool for managing the absence of elements in Python collections, allowing for error prevention, data integrity assurance, and resource access control.Using 'in' and 'not in' with different Python types
in and not in operators prove to be extremely versatile in Python, as they can be applied to various data types. Let's examine how these operators interact with different types of Python structures.Lists
in and not in. These operators allow checking for the presence of an element:Strings
in and not in check for the presence of substrings:Tuples
in and not in:Dictionaries
in and not in check for the presence of keys by default, but can also be used with .values() and .items() to check for values or pairs:Sets
in and not in due to their efficiency:in and not in with various data types in Python offers great flexibility and simplifies many programming tasks, from text processing to managing complex collections.Concrete examples of using the 'in' and 'not in' operators
in and not in operators, here are some concrete examples that show how these tools can be integrated into real programming scenarios.Data filtering
not in can be used to quickly filter out undesirable items.Unique ID validation
in can be used to ensure that a new identifier is not already in use:Text analysis
in is often used to search for specific words or phrases:Access management
not in can be used to check if a user does not have access to a particular resource:in and not in operators in Python, enabling developers to simplify their code and make verification operations more efficient and readable.Replacing chained 'or' operators
or operators to check if a value matches multiple options. However, using in and not in can simplify and make the code more readable and efficient.Classic usage of or
fruit is one of the fruits you are looking for:Simplification with in
or operators with in, the code becomes more concise:Advantages of using in
in offers several advantages:- Readability: The code is easier to understand, especially when there are many options.
- Scalability: Adding or removing options in the list is simple and does not require modifying the conditional logic.
- Performance: With data structures like sets, membership checking is optimized, which can provide performance gains.
Complex case with not in
not in can be used to simplify complex expressions with or:not in is used to ensure that fruit does not belong to a list of specific items, in a concise and efficient manner.or operators with in and not in, the code becomes not only clearer but also easier to manage and adapt to future changes.Writing efficient membership tests
in and not in operators wisely, it is possible to perform quick and accurate checks. Here are some best practices to achieve this.Choosing the right data structure
set) and dictionaries are generally more performant than lists and tuples for membership checks:Prefer lists for small collections
Using list comprehensions
Optimization with nested conditions
in and not in with other conditions can optimize control flow:Using 'operator.contains()' for membership tests
operator.contains() in Python provides a powerful and sometimes more explicit alternative for performing membership tests. This function is part of the operator module, which provides functions equivalent to Python's intrinsic operators.Understanding operator.contains()
operator.contains(container, item) is used to check if an item is present in a container. It returns True if the item is found; otherwise, it returns False. This function is equivalent to using item in container, but it can be useful in certain contexts, especially when using functions like map() or filter().Using in functions
map() or filter(), operator.contains() can be used to make the code more readable and avoid lambda function definitions:operator.contains() can be used to enhance clarity when integrated into functional programming constructs.Comparison with in
operator.contains() is not necessary in simple cases, it offers a more explicit semantics that can be beneficial in complex contexts or for developers who prefer a functional approach:Conclusion on using operator.contains()
in operator is more natural and often sufficient, operator.contains() offers a valuable alternative in situations where a functional approach is preferred, thus enhancing code modularity and readability. This demonstrates Python's flexibility to cater to different programming styles and specific needs.Support for membership tests in user-defined classes
in and not in operators in your own Python classes, you need to implement the special method __contains__. This method is called by Python to determine if an element belongs to an instance of your class. Here’s how you can proceed.Implementing __contains__
__contains__ method. Let's imagine we have a Library class that contains a collection of books:__contains__ method checks if a book is present in the library's collection of books.Using in code
__contains__ method implemented, you can use the in and not in operators naturally with instances of your class:Advantages of using __contains__
__contains__ has several advantages:- Readability: It allows for idiomatic Python syntax, making the code easier to understand.
- Encapsulation: It keeps the membership logic encapsulated within the class, facilitating code maintenance and evolution.
- Flexibility: You can customize the membership logic to meet the specific needs of your application.
__contains__, your classes can easily integrate into the Python ecosystem, using concepts and operators that are already familiar to developers. This not only enhances the coding experience but also improves the robustness and reusability of your code.Conclusion
in and not in are essential tools in Python, providing a simple and intuitive way to check for the presence or absence of elements in sequences and other data structures. Their effective use can simplify code, enhance readability, and optimize performance.Key takeaways
- Versatility: These operators apply to various data types, from lists to sets, dictionaries, and strings. Their ability to adapt to different contexts makes them indispensable for any Python developer.
- Optimization: Using
inandnot inwith the right data structures, such as sets for large collections, can significantly improve code efficiency. Choosing the right structure based on data size and complexity is crucial for maintaining optimal performance. - Simplicity: The ability to replace chains of
oroperators withinenhances readability and reduces code complexity. This simplification is particularly useful when handling many conditions or checks.
Integration into custom classes
__contains__, developers can extend these functionalities to user-defined classes, making the code more consistent and integrated with the Python language. This integration allows for a more intuitive and idiomatic use of custom classes, facilitating their adoption and use in larger projects.Functional approach
operator.contains() provides a functional alternative for membership tests, allowing greater flexibility in contexts where functions need to be passed as arguments or used in functional expressions.in and not in operators is essential for fully leveraging the power and flexibility of the Python language.Want to go further?
This topic is part of our Become a Data Analyst course. Browse the full programme, or get it by email.
Share with

Romain DE LA SOUCHÈRE
Tech Lead, CTO AXI Technologies
Expert Data Engineering et Cloud, Romain affiche plus de 11 ans d'expérience, dont plusieurs années comme Lead Developer sur des solutions Smart Building haute performance. Il y a conçu et mis en production des moteurs de traitement capables d'absorber des centaines de milliers de données de capteurs par minute, ainsi que des bases clusterisées gérant plus de 10 millions de données dynamiques. Certifié Microsoft Azure DevOps Engineer Expert, il maîtrise aussi bien le développement back-end (Python, C#) que le DevOps (Docker, Kubernetes, Terraform) et les agents LLM. Formateur en Python, cloud, DevOps et IA générative appliquée, il forme avec une obsession : Amener chaque apprenant à concevoir et déployer des architectures réellement scalables en production.
» Learn MoreAssociated trainings
All our trainings →
Associated articles
See all our articles →



