If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Python, membership test operators are used to check if a value exists within a collection, such as a list, tuple, set, or string. These operators allow you to determine if a particular element is present in the given collection. There are two membership test operators in Python:
in
operator: Thein
operator returnsTrue
if the specified value is present in the collection, andFalse
otherwise.Example:
pythonCopy code
# List membership test numbers = [1, 2, 3, 4, 5] print(3 in numbers) # Output: True print(6 in numbers) # Output: False # String membership test text = "Hello, World!" print("Hello" in text) # Output: True print("Python" in text) # Output: False
In this example, the
in
operator is used to check if the values 3 and 6 are present in the listnumbers
, and the values "Hello" and "Python" are present in the stringtext
.
not in
operator: Thenot in
operator is the negation of thein
operator. It returnsTrue
if the specified value is not present in the collection, andFalse
if the value is present.Example:
pythonCopy code
# Tuple membership test fruits = ("apple", "banana", "orange") print("apple" not in fruits) # Output: False print("grape" not in fruits) # Output: True
In this example, the
not in
operator is used to check if the values "apple" and "grape" are present in the tuplefruits
.Membership test operators are commonly used to check for the existence of specific elements in collections before performing certain actions or making decisions based on their presence. They are particularly useful when dealing with lists, tuples, sets, and strings in Python.
Comments: 0