Использование Python: Как легко устранить проблемы с отсутствием ключевого слова
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.
In this tutorial, you’ll learn how to:
- Perform membership tests using the
in
andnot in
operators - Use
in
andnot in
with different data types - Work with
operator.contains()
, the equivalent function to thein
operator - Provide support for
in
andnot in
in your own classes
To get the most out of this tutorial, you’ll need basic knowledge of Python, including built-in data types, such as lists, tuples, ranges, strings, sets, and dictionaries. You’ll also need to know about Python generators, comprehensions, and classes.
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:
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 (==
).
These are slightly different but commonly used ways to compare values in Python. While the is
operator checks if two objects refer to the exact same memory location, the ==
operator compares the values of two objects. In most cases, you’ll use the ==
operator for membership tests.
Let’s see how this function works with some examples:
Here, the function returns True
if the target value is found in the collection and False
otherwise. You can use this function to perform membership tests with any iterable collection. However, Python provides a more convenient and expressive way to do this: the in
and not in
operators.
Python’s in
Operator
The in
operator allows you to check if a value is a member of a collection. Its syntax is as follows:
Here, value
is the value you want to check, and collection
is the collection of values. The in
operator returns True
if value
is found in collection
and False
otherwise.
Let’s rewrite the previous examples using the in
operator:
The output will be the same as before:
As you can see, using the in
operator simplifies the code and makes it more readable.
Python’s not in
Operator
The not in
operator allows you to check if a value is not a member of a collection. Its syntax is as follows:
Here, value
is the value you want to check, and collection
is the collection of values. The not in
operator returns True
if value
is not found in collection
and False
otherwise.
Let’s rewrite the previous examples using the not in
operator:
The output will be the same as before:
Using the not in
operator provides a more intuitive way to perform the “not in” membership test.
Using in
and not in
With Different Python Types
You can use the in
and not in
operators with various built-in types in Python, including:
- Lists, Tuples, and Ranges
- Strings
- Generators
- Dictionaries and Sets
Let’s take a closer look at each of these types and demonstrate how to use the in
and not in
operators with them.
Lists, Tuples, and Ranges
Lists, tuples, and ranges are sequence types in Python. You can use the in
and not in
operators to check if an element exists in these sequences.
Here are a few examples:
For lists and tuples, the in
operator checks if the element is present in the sequence, while the not in
operator checks if the element is not present.
For ranges, the in
operator checks if the element is within the range, while the not in
operator checks if the element is not within the range.
Strings
Strings are also sequence types in Python, which means you can use the in
and not in
operators to check if a character or substring exists in a string.
Here are a few examples:
The in
operator checks if the character or substring is present in the string, while the not in
operator checks if it is not present.
Generators
Generators are objects that can be iterated over to produce a sequence of values. You can use the in
and not in
operators with generators just like any other iterable object.
Here’s an example:
The in
and not in
operators iterate over the values produced by the generator until they find the target value or reach the end of the sequence. Keep in mind that once you iterate over a generator, you can’t iterate over it again. Therefore, it’s important to consider the order of your membership tests.
Dictionaries and Sets
Dictionaries and sets are unordered collections of values. You can use the in
and not in
operators to check if a value is present in a dictionary or set.
Here are a few examples:
For dictionaries, the in
operator checks if the target value is a key in the dictionary, while the not in
operator checks if it is not a key.
For sets, both the in
and not in
operators check if the target value is present in the set.
Putting Python’s in
and not in
Operators Into Action
Now that you understand the basics of using the in
and not in
operators, let’s explore some practical use cases where these operators can be very useful.
Replacing Chained or Operators
In some cases, you may need to check if a value is equal to one of several possible values. Traditionally, you would have to use multiple or
operators to achieve this. However, with the in
operator, you can simplify the code and make it more readable.
Consider the following example:
This code checks if the value of name
is equal to either 'Alice'
, 'Bob'
, or 'Charlie'
. The same logic can be expressed more concisely using the in
operator:
By using the in
operator, you can avoid the repetitive or
operators and create a cleaner and more maintainable code.
Writing Efficient Membership Tests
Python’s in
and not in
operators are very efficient when used with built-in types, like lists, tuples, and sets. However, for large collections or custom objects, there are more efficient alternatives.
If performance is a concern, you can use the operator.contains()
function from the operator
module. This function provides an equivalent functionality to the in
operator but can sometimes perform better on certain objects.
Here’s an example:
The operator.contains()
function works the same way as the in
operator, but it can optimize the membership test based on the type of object being tested.
Keep in mind that for most cases, the in
operator is efficient enough and produces readable code. However, if you experience performance issues, consider using operator.contains()
as an alternative.
Supporting Membership Tests in User-Defined Classes
If you define your own classes in Python, you can provide support for membership tests by implementing the __contains__()
method. This method allows you to customize the behavior of the in
and not in
operators with instances of your class.
Here’s an example:
In this example, the Person
class defines the __contains__()
method, which checks if the target value is equal to the name
attribute of the Person
object.
By implementing this method, you can control how membership tests are performed with instances of your class.
Conclusion
The in
and not in
operators are powerful tools in Python for performing membership tests with different types of collections. They provide a more convenient and expressive way to check if a value is present in a collection, and they can simplify your code and make it more readable.
In this tutorial, you’ve learned how to use the in
and not in
operators with various data types, including lists, tuples, ranges, strings, generators, dictionaries, and sets. You’ve also seen how to replace chained or
operators with the in
operator, how to write efficient membership tests using operator.contains()
, and how to support membership tests in your own classes.
By mastering the in
and not in
operators, you’ll have a powerful tool at your disposal for working with collections and performing membership tests in Python. Happy coding!