Back to Python
2026-01-046 min read

Example 5: Membership operators in Python

Learn Example 5: Membership operators in Python step by step with clear examples and exercises.

Title: Membership Operators in Python: A full guide for Practical Depth

Why This Matters

In programming, membership operators are essential tools that help us check if a specific value or data structure exists within another. They play a crucial role in various scenarios such as validating user input, checking for duplicate values, and optimizing loops. Understanding these operators can significantly improve your problem-solving skills and help you write more efficient code.

Prerequisites

To fully grasp the concepts of membership operators in Python, it is essential to have a solid understanding of:

  1. Basic Python syntax (variables, data types, operators)
  2. Control structures (if statements, for loops, while loops)
  3. Data structures (lists, tuples, and dictionaries)
  4. Understanding the difference between mutable and immutable objects in Python
  5. Familiarity with common Python libraries such as collections and itertools

Core Concept

Python provides three membership operators: in, not in, and is. Let's explore each one with examples and use cases.

The in Operator

The in operator checks if a value or variable is found within an iterable (list, tuple, set, string, etc.). It can be used to check for elements in containers, words in strings, or even specific characters in strings.

numbers = [1, 2, 3, 4, 5]
if 3 in numbers:
print("3 is present in the list.")
else:
print("3 is not present in the list.")

Checking for elements in a dictionary

my_dict = {"apple": 1, "banana": 2, "orange": 3}

if "apple" in my_dict:

print("The fruit 'apple' is found in the dictionary.")

else:

print("The fruit 'apple' is not found in the dictionary.")

Checking for words in a string

sentence = "Hello, World!"

if "World" in sentence.split():

print("The word 'World' is present in the sentence.")

else:

print("The word 'World' is not present in the sentence.")


### The `not in` Operator

The `not in` operator checks whether a value or variable is **not** found within an iterable. It can be used to check for missing elements in containers, non-existent words in strings, or specific characters that are not present in strings.

numbers = [1, 2, 3, 4, 5]

if 6 not in numbers:

print("6 is not present in the list.")

else:

print("6 is present in the list.")

Checking for missing elements in a dictionary

my_dict = {"apple": 1, "banana": 2, "orange": 3}

if "grape" not in my_dict:

print("The fruit 'grape' is not found in the dictionary.")

else:

print("The fruit 'grape' is found in the dictionary.")

Checking for non-existent words in a string

sentence = "Hello, World!"

if "Hi" not in sentence.split():

print("The word 'Hi' is not present in the sentence.")

else:

print("The word 'Hi' is present in the sentence.")


### The `is` Operator

The `is` operator checks if two variables refer to the same object. This is different from comparing their values using the `==` operator. It can be used to check for identity, not equality.

a = [1, 2, 3]

b = [1, 2, 3]

c = a

print(a is c) # True because 'c' refers to the same object as 'a'

print(a is b) # False because 'a' and 'b' refer to different objects with the same value

Worked Example

Let's create a simple program that checks if a user-entered word is found in a list of common English words. We will use the collections.Counter function from the collections library to count the frequency of each word in a predefined list of common English words.

import collections
common_words = collections.Counter(open("common_english_words.txt").read().split())
user_word = input("Enter a word: ")

if user_word in common_words:
print(f"Your word, '{user_word}', is found in the list of common English words.")
else:
print(f"Your word, '{user_word}', is not found in the list of common English words.")

In this example, we use the collections.Counter function to create a dictionary where each key is a word and its corresponding value is the frequency of that word in our list of common English words. We then check if the user-entered word exists as a key in this dictionary using the in operator.

Common Mistakes

  1. Mistaking the is operator for equality comparison (==): Remember that the is operator checks if two variables refer to the same object, while == compares their values. Using the is operator with mutable objects can lead to unexpected results because changing one object will change both objects that refer to it.
  1. **Not understanding the difference between in and membership functions like list.count() or set.intersection():** The in operator is a simple, fast way to check if an item exists in an iterable. On the other hand, functions like list.count() and set.intersection() offer additional functionality but may be slower for large datasets.
  1. Using the is operator with mutable objects like lists: Using the is operator with mutable objects can lead to unexpected results because changing one object will change both objects that refer to it. It's generally better to compare their contents using the == operator instead.
  1. Not considering the case sensitivity of strings when checking membership: By default, Python string comparison is case-sensitive, so if you are comparing strings, make sure they have the same case or use the lower() method to convert both strings to lowercase before comparing them.

Practice Questions

  1. Write a program that checks if a user-entered number is between 1 and 100 (inclusive). Use the range() function to create an iterable of numbers from 1 to 100, then use the in operator to check if the user's input is in this range.
  1. Create a function that takes a list of numbers as input and returns a new list containing only the odd numbers. Use the is operator to optimize your solution by checking if a number is not divisible by 2 before adding it to the resulting list.
  1. Write a program that checks if a user-entered word is found in a dictionary of common English words (you can find such dictionaries online). Use the collections.Counter function to create a dictionary of common English words, then check if the user's input exists as a key in this dictionary using the in operator.
  1. Create a function that takes two lists as input and returns True if both lists contain the same elements, regardless of their order. Use the set() function to convert both lists into sets, then use the == operator to compare the resulting sets.

FAQ

  1. What is the difference between the in operator and the == operator in Python? The in operator checks if a value or variable is found within an iterable, while the == operator compares their values directly.
  1. Can I use the is operator with lists or other mutable objects? Using the is operator with mutable objects can lead to unexpected results because changing one object will change both objects that refer to it. It's generally better to compare their contents using the == operator instead.
  1. Is there a way to check if an item is not in a list without using the not in operator? Yes, you can use the not keyword with the in operator to achieve this: if item not in my_list.
  1. What are some common pitfalls when using membership operators in Python? Some common mistakes include mistaking the is operator for equality comparison (==), not understanding the difference between in and other membership functions, and using the is operator with mutable objects like lists. Additionally, it's important to consider case sensitivity when working with strings and understand the differences between various data structures and their membership functions.
Example 5: Membership operators in Python | Python | XQA Learn