Home » Python Membership Operators: A Tutorial

Python Membership Operators: A Tutorial

Membership operators in Python are used to test whether a value or variable is a member of a sequence, such as a string, list, tuple, set, or dictionary.

These operators evaluate to True or False, depending on whether the specified value is present in the sequence or not.

There are two membership operators in Python:

in: Returns True if the value is found in the sequence.
not in: Returns True if the value is NOT found in the sequence.

1. Python Membership Operators Syntax

in: Checks if an element exists in a sequence.
not in: Checks if an element does NOT exist in a sequence.

2. Using Membership Operators with Different Data Types

a) Using in and not in with Strings

Strings are sequences of characters. You can use membership operators to check whether a particular substring exists within a string.

# Example of using 'in' with strings
text = "Hello, world!"

# Check if 'Hello' is in the string
result = "Hello" in text
print(result)  # Output: True

# Check if 'Python' is in the string
result = "Python" in text
print(result)  # Output: False

# Example of using 'not in' with strings
result = "Python" not in text
print(result)  # Output: True

b) Using in and not in with Lists

Lists are ordered collections of elements. You can check for the presence or absence of an item in a list.

# Example of using 'in' with lists
numbers = [1, 2, 3, 4, 5]

# Check if 3 is in the list
result = 3 in numbers
print(result)  # Output: True

# Check if 10 is in the list
result = 10 in numbers
print(result)  # Output: False

# Example of using 'not in' with lists
result = 10 not in numbers
print(result)  # Output: True

c) Using in and not in with Tuples

Tuples are similar to lists but are immutable (cannot be changed). Membership operators work similarly with tuples.

# Example of using 'in' with tuples
colors = ("red", "green", "blue")

# Check if 'green' is in the tuple
result = "green" in colors
print(result)  # Output: True

# Check if 'yellow' is in the tuple
result = "yellow" in colors
print(result)  # Output: False

# Example of using 'not in' with tuples
result = "yellow" not in colors
print(result)  # Output: True

d) Using in and not in with Sets

Sets are unordered collections of unique elements. Membership operators can check if a value is present in a set.

# Example of using 'in' with sets
my_set = {1, 2, 3, 4, 5}

# Check if 4 is in the set
result = 4 in my_set
print(result)  # Output: True

# Check if 10 is in the set
result = 10 in my_set
print(result)  # Output: False

# Example of using 'not in' with sets
result = 10 not in my_set
print(result)  # Output: True

e) Using in and not in with Dictionaries

For dictionaries, membership operators check the presence of keys, not values.

# Example of using 'in' with dictionaries
my_dict = {"name": "Alice", "age": 25, "city": "New York"}

# Check if 'name' is a key in the dictionary
result = "name" in my_dict
print(result)  # Output: True

# Check if 'Alice' is a key in the dictionary (it checks keys, not values)
result = "Alice" in my_dict
print(result)  # Output: False

# Example of using 'not in' with dictionaries
result = "city" not in my_dict
print(result)  # Output: False

To check for the presence of a value in a dictionary, you need to use the values() method.

# Check if 'Alice' is a value in the dictionary
result = "Alice" in my_dict.values()
print(result)  # Output: True

3. Practical Examples Using Membership Operators

a) Check if a Substring is Present in a Sentence

This program checks whether a specific word is present in a sentence.

sentence = "Python is an awesome programming language."

# Check if the word 'awesome' is in the sentence
if "awesome" in sentence:
    print("The word 'awesome' is present in the sentence.")
else:
    print("The word 'awesome' is not present in the sentence.")

b) Check if an Element Exists in a List

Let’s check whether a number exists in a list.

numbers = [10, 20, 30, 40, 50]

# Ask the user for a number and check if it's in the list
user_input = int(input("Enter a number: "))

if user_input in numbers:
    print(f"{user_input} is in the list.")
else:
    print(f"{user_input} is not in the list.")

c) Check if a Key Exists in a Dictionary

This program checks whether a given key exists in a dictionary.

# Sample dictionary
person = {"name": "Bob", "age": 30, "job": "Engineer"}

# Check if a key exists
if "name" in person:
    print("The key 'name' exists in the dictionary.")
else:
    print("The key 'name' does not exist in the dictionary.")

d) Check for Substring Presence in User Input

This program checks if a user’s input contains a specific word.

# Ask the user to enter a sentence
user_input = input("Enter a sentence: ")

# Check if the word 'Python' is in the input
if "Python" in user_input:
    print("You mentioned Python!")
else:
    print("You did not mention Python.")

e) Check if a Character is in a String

This example checks whether a character is present in a given string.

# String of vowels
vowels = "aeiou"

# Input a character from the user
char = input("Enter a character: ").lower()

# Check if the character is a vowel
if char in vowels:
    print(f"{char} is a vowel.")
else:
    print(f"{char} is not a vowel.")

f) Check if an Item is in a Shopping List

This example checks if an item is present in a shopping list.

# Shopping list
shopping_list = ["milk", "eggs", "bread", "butter"]

# Input an item from the user
item = input("Enter an item: ").lower()

# Check if the item is in the shopping list
if item in shopping_list:
    print(f"{item.capitalize()} is already in the shopping list.")
else:
    print(f"{item.capitalize()} is not in the shopping list.")

4. Combining Membership Operators with Loops

You can combine membership operators with loops for more complex operations, such as searching through a list of items.

Example: Finding Common Items Between Two Lists

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

# Find common items between two lists
common_items = [item for item in list1 if item in list2]
print(f"Common items: {common_items}")  # Output: [4, 5]

Example: Filter Items Not in Another List

list1 = ["apple", "banana", "cherry"]
list2 = ["banana", "kiwi"]

# Filter items in list1 that are not in list2
unique_items = [item for item in list1 if item not in list2]
print(f"Unique items in list1: {unique_items}")  # Output: ['apple', 'cherry']

Summary

in and not in: These membership operators check if a value exists (or doesn’t exist) within sequences like strings, lists, tuples, sets, and dictionaries.
Membership operators return True or False, making them useful for conditional statements and loops.
Membership operators work with different data structures, and you can combine them with loops and conditionals for powerful logic in your programs.

By understanding and using membership operators effectively, you can write more readable and efficient Python programs that check for the presence or absence of values within sequences.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More