MEMBERSHIP OPERATORS IN PYTHON
Now, we are going to learn about the membership operators in Python. Basically, as the name suggests, the membership operators are used to check whether or not some value is a member of some sequence. This is like we are checking whether there is ‘P’ in Python.
As the membership operators, we have the in and not in operators. Here is the table, with the operators, their descriptions, and example. Soon, we would also discuss a simple program, which demonstrates the membership operators.
For the example in the table, we consider the list games = [“Cricket”, “Hockey”, “Kabaddi”]. This is a list, and list is nothing but a collection of data, about which we are going to learn soon.
Operator | Description | Example |
in | This operator checks whether the specified value is present in a sequence. | print(“Cricket” in games) this will print True, as a string named “Cricket” is present in the list games. |
not in | This operator checks whether the specified value is not present in a sequence. | print(“Apple” not in games) this will print True, as the string named “Apple” is not present in the list games. |
Now, let’s have a look at a simple program, which demonstrates the above-discussed membership operators.
As you can see, we have a string, and then we are checking for the membership of some element in the sequence like we are first checking if ‘P’ is there in the string, which comes out to be True, and then we are also checking if ‘G’ is not there in string, which again comes out to be True. So, have a look at the output of the given program.
True
True
As you can see, in both cases, we got True, as our output. There would be many situations in our programs, where we would use the membership operators. We would use the membership operators as and when required, and you can try them for other things as well, like the list, tuples, etc., as we would learn them later.