Python membership operators
Created By: chatGPT
In Python, membership operators are used to test for membership in a sequence, such as a list, tuple, or string. The two membership operators are
in
and not in
. These operators help in determining whether a certain value exists within a collection.my_list = [1, 2, 3, 4, 5]
# Using 'in' operator
if 3 in my_list:
print('3 is in the list')
# Using 'not in' operator
if 6 not in my_list:
print('6 is not in the list')
Here’s a brief explanation of how each operator works:
- The
in
operator checks if a specified value is found within the provided sequence. If the value exists, it returnsTrue
; otherwise, it returnsFalse
. - The
not in
operator checks if a specified value is not present in the sequence. If the value does not exist, it returnsTrue
; if it does, it returnsFalse
.
my_string = 'Hello World'
# Check if 'Hello' is in the string
if 'Hello' in my_string:
print('Found Hello')
# Check if 'bye' is not in the string
if 'bye' not in my_string:
print('Bye not found')
These operators can be very useful when you're working with collections of data and need to make decisions based on the presence or absence of certain elements. Using membership operators can make your code cleaner and more intuitive, improving readability.
my_tuple = (10, 20, 30)
# Using 'in' with a tuple
if 20 in my_tuple:
print('20 is in the tuple')
# Using 'not in' with a tuple
if 40 not in my_tuple:
print('40 is not in the tuple')