Skip to content
Home » Blog » What Are Membership Operators in Python and How Do They Work?

What Are Membership Operators in Python and How Do They Work?

Introduction

Let me share something from when I was first learning Python.

I kept seeing the word in, and I didn’t really get what it meant. For example:

'apple' in ['apple', 'banana', 'cherry']

At first, I thought it was just part of a sentence. But then I realized—it’s actually checking if “apple” is in the list. It’s kind of like asking, “Is my name on the list?”

That’s when I learned about membership operators in Python. They help you check if something is inside a collection, like a list, string, or dictionary. There are just two of them: in and not in.

Once I understood how they work, I started using them all the time—for checking if an item is in a list, a letter in a word, or a key in a dictionary.

In this post, I’ll show you exactly what these operators do, how they work, and give you simple examples. Don’t worry, we’ll take it step by step!

Let’s get started.

What Are Membership Operators in Python?

Membership operators in Python let you check if a specific item exists within a collection—like a list, string, or dictionary.
These collections act like containers that hold multiple items.
With membership operators, you can quickly test if something is inside or not inside these containers.
It’s a simple way to ask, “Is this item part of the group?”

The two membership operators you’ll use in Python are:

  1. in: Checks if a value is inside a collection.
  2. not in: Checks if a value is not inside a collection.

For example, let’s look at this:

'apple' in ['apple', 'banana', 'cherry']

This checks if ‘apple’ is inside the list ['apple', 'banana', 'cherry']. The answer is True because, yes, apple is indeed in that list.

But if we check for something that’s not there:

'grape' in ['apple', 'banana', 'cherry']

It would return False because grape isn’t in that list.

So, this is the power of the in operator. It lets you quickly check if something is part of a collection.

Flowchart showing how Python evaluates in and not in membership operators.
Flowchart explaining how Python returns True or False based on membership checks using in and not in.

Why Membership Operators Matter in Real Code

Now that you know what the operators do, why does it matter in real code?

Think about it: when you’re building a program, you might need to check if something already exists before doing something with it. For example, let’s say you’re creating a list of students, and you want to see if a student has already been added before allowing them to sign up again. Instead of writing complicated code, you can just use the in operator.

Here’s an example:

students = ['John', 'Jane', 'Mike']
'Jane' in students  # Returns True because 'Jane' is in the list
'Chris' in students  # Returns False because 'Chris' is not in the list

This simple check helps you avoid mistakes like adding the same person twice, making your code cleaner and easier to read.

Where in and not in Work Best

Let’s talk about where these operators work best. They’re really handy in different situations. You can use in and not in with:

  • Lists: To check if a value is in a list of items.
  • Strings: To check if a substring is inside a string.
  • Dictionaries: To check if a key exists in a dictionary.

1. In a List

Imagine you have a list of favorite fruits:

fruits = ['apple', 'banana', 'cherry']

Now, let’s check if a fruit is in the list:

'banana' in fruits  # Returns True because 'banana' is in the list

But if we check for something that’s not there:

'grape' in fruits  # Returns False because 'grape' is not in the list

2. In a String

Let’s say you have a sentence, and you want to check if a word is in it. Here’s how you can do that:

sentence = "Python is awesome"
'awesome' in sentence  # Returns True because 'awesome' is in the sentence
'great' in sentence  # Returns False because 'great' is not in the sentence

3. In a Dictionary (Checking for Keys)

With dictionaries, membership operators check for keys—not values. For instance, if you have a dictionary with student details:

student_info = {'name': 'Alice', 'age': 25}

You can check if a key, like 'name', exists:

'name' in student_info  # Returns True because 'name' is a key in the dictionary

But if you check for a key that doesn’t exist:

'email' in student_info  # Returns False because 'email' is not a key in the dictionary

And if you want to check if a key isn’t there, use not in:

'email' not in student_info  # Returns True because 'email' is not a key

Python in Operator with Strings, Lists, and Tuples

In Python, the in operator is super useful when you’re working with strings, lists, or tuples. It helps you easily check if something exists inside these collections. Let’s break it down for each type of collection.

Checking Substrings in a String

Table showing how different substrings are evaluated with the in operator in a sample string.
Substring membership checks in the string “EmiTechLogic” using Python’s in operator.

Okay, let’s start with strings. You know how we have sentences made of words, right? Now, the in operator can help you figure out if a specific word or substring is in that sentence.

For example, imagine you have a sentence like this:

sentence = "Python is a great programming language"

Now, let’s say you want to check if the word “great” is in the sentence. You can do that using the in operator:

'great' in sentence  # This checks if 'great' is in the sentence

This will return True because, yes, the word “great” appears in the sentence.

But what if you check for something that isn’t in the sentence, like “awesome”?

'awesome' in sentence  # This checks if 'awesome' is in the sentence

This will return False because “awesome” isn’t part of the sentence.

So, with strings, the in operator is like asking: “Is this word or letter inside my sentence?” It’s super handy for searches.

Finding Elements in Lists

Table comparing values (including floats) against a list using Python’s in and not in operators.
Membership checks in a list with integers and floats using in and not in.

Now, let’s talk about lists. A list is basically just a collection of things—numbers, words, anything! You might have a list of fruits like this:

fruits = ['apple', 'banana', 'cherry']

Now, let’s say you want to check if “banana” is in this list. You can use the in operator like this:

'banana' in fruits  # This checks if 'banana' is in the list

This will return True because banana is indeed in the list.

But what if you check for something that’s not in the list, like “orange”?

'orange' in fruits  # This checks if 'orange' is in the list

This will return False because orange isn’t part of the list.

So, with lists, it’s like asking: “Is this item part of my collection?” It helps you quickly check if something is there.

Matching Tuples or Sub-Tuples

Next up, tuples! Tuples are very similar to lists, but they’re immutable, which means once you create a tuple, you can’t change its contents. But you can still use the in operator with tuples, just like lists.

Let’s say you have a tuple like this:

numbers = (1, 2, 3, 4, 5)

Now, if you want to check if 3 is in this tuple, you can use:

3 in numbers  # This checks if 3 is in the tuple

This will return True because 3 is in the tuple.

But here’s something cool: What if you want to check for a sub-tuple? That means checking if a small group of elements is inside a larger tuple. Here’s how you do it:

nested_tuple = (1, 2, (3, 4), 5)
(3, 4) in nested_tuple  # This checks if the sub-tuple (3, 4) is in the tuple

This will return True because the sub-tuple (3, 4) is indeed inside the nested_tuple.

So, with tuples, the in operator works for both individual elements and even small groups (sub-tuples) inside larger tuples!

Recap

  • strings, the in operator checks if a specific word or part of a word (substring) is inside the string.
  • lists, it checks if an element exists in the list.
  • tuples, it checks both for individual elements and even small groups (sub-tuples).

These simple checks are so helpful when you’re writing code, and they make your job a lot easier. It’s like having a quick way to ask, “Is this here?” without writing a bunch of extra code.

Alright, let’s dive into the not in operator in Python! If the in operator helps you check if something is in a collection, the not in operator does the opposite—it checks if something is not in a collection.


Must Read


Python not in Operator: The Opposite Logic

Just like the in operator, not in is really simple to use. It helps you check if a particular item is not present in a string, list, tuple, or any other collection.

For example:

fruits = ['apple', 'banana', 'cherry']
'orange' not in fruits  # This checks if 'orange' is NOT in the list

This will return True because orange is not in the list.

When to Use not in Over in

Now, you might wonder: when should you use not in instead of just in? It all comes down to the logic you need.

  • Use not in when you want to check if something doesn’t exist in a collection.
  • Use in when you want to check if something does exist in a collection.

Let’s look at an example. Imagine you have a list of fruits, and you want to know if “apple” is not in the list. You’d use not in like this:

fruits = ['banana', 'cherry', 'orange']
'apple' not in fruits  # Checks if 'apple' is NOT in the list

This will return True because apple isn’t in the list of fruits.

But if you checked “orange” like this:

'orange' not in fruits  # Checks if 'orange' is NOT in the list

This will return False because orange is in the list.

In short: if you’re looking for the absence of something, not in is your friend!

Avoiding Common Pitfalls with not in

Even though not in is simple to use, there are some things to be careful about so you don’t run into issues:

  1. Mixing up in and not in: It’s easy to accidentally switch them. If you’re trying to check if something is not in a collection, remember to use not in. Otherwise, you might get the wrong result. For example, this:
fruits = ['apple', 'banana', 'cherry']
'apple' in fruits  # This returns True, because 'apple' is in the list

But if you’re looking for the absence of apple, you should use:

'apple' not in fruits  # This returns False, because 'apple' is in the list

Checking for not in with nested collections: If you’re checking for something inside a list of lists or a tuple of tuples, be careful. The not in operator checks for membership at the outer level only.

For example:

nested_list = [[1, 2], [3, 4], [5, 6]]
[7, 8] not in nested_list  # Returns True because [7, 8] is not in the list

But if you wanted to check for something deeper inside one of the sub-lists, you’d need to manually check each sub-list.

Recap

  • The not in operator is the opposite of in. It checks if an element is not in a collection.
  • Use not in when you need to check for the absence of something.
  • Be careful when using it with nested collections, and make sure to double-check the logic when switching between in and not in.

If you’re trying to check for something that isn’t in your collection, not in makes your code cleaner and more intuitive.

Membership Checks in Sets and Dictionaries

How Python Checks Membership in Sets

Set membership diagram showing a tuple being matched exactly within a Python set.
Exact-match membership check in a Python set using a tuple.

First up, let’s talk about sets. Sets in Python are unordered collections of unique items. That means they don’t care about order, and they don’t allow duplicates.

Let’s look at an example:

fruits = {'apple', 'banana', 'cherry'}

Now, if you want to check if “banana” is in this set, you can use the in operator just like we did with lists:

'banana' in fruits  # Checks if 'banana' is in the set

This will return True because “banana” is in the set.

But what about if you check for something that’s not in the set, like “orange”?

'orange' in fruits  # Checks if 'orange' is in the set

This will return False because “orange” is not in the set.

Why in Works Only with Keys in Dictionaries

Diagram showing that only keys are checked for membership in Python dictionaries.
Membership check in a dictionary showing that only keys are considered in Python.

Next, let’s talk about dictionaries. Dictionaries in Python store data in key-value pairs. This is different from a list or set because a dictionary links a key to a value.

Here’s an example:

person = {'name': 'Alice', 'age': 25, 'city': 'New York'}

Now, if you want to check if the key ‘name’ exists in this dictionary, you can use the in operator like this:

'name' in person  # Checks if 'name' is a key in the dictionary

This will return True because ‘name’ is one of the keys in the dictionary.

But, if you check for a value—like checking if ‘Alice’ is one of the values in the dictionary—you’ll get something unexpected if you use in directly like this:

'Alice' in person  # This won’t work as expected for values

This will return False because Python is looking for ‘Alice’ as a key, not as a value.

Can You Check for Values in a Dictionary? (Trick Alert)

Here’s a little trick: While in only works for checking keys in dictionaries, you can still check for values. But it’s not as straightforward as just using in on the dictionary itself. You need to use the .values() method, which returns a list of all the values in the dictionary.

For example, let’s check if ‘Alice’ is one of the values in the person dictionary:

'Alice' in person.values()  # Checks if 'Alice' is in the values of the dictionary

This will return True because ‘Alice’ is a value in the dictionary.

Recap

  • In sets, you can use in to check if an item is part of the set, just like with lists and tuples.
  • In dictionaries, in works to check if a key exists. It doesn’t check the values directly.
  • To check if a value exists in a dictionary, use .values() in combination with the in operator.

This might seem a bit tricky at first, but once you get the hang of it, you’ll be using in and not in with sets and dictionaries easily!

Alright, let’s bring everything we’ve learned about membership operators into some real-world use cases. These are situations where you’ll actually use the in and not in operators to solve practical problems in Python. These examples will make it easier for you to see how these operators work in everyday coding tasks.

Real-World Use Cases You’ll Actually Use

User Input Validation

One common use for the in and not in operators is user input validation. For instance, imagine you’re building a system where users need to enter a specific value from a list of options. Instead of just assuming the input is correct, you can use in to check if the user’s input matches one of the valid options.

Let’s say you have a program that lets users choose a color, and the valid colors are red, green, and blue. You can validate their input like this:

valid_colors = ['red', 'green', 'blue']
user_input = input("Choose a color: ")

if user_input in valid_colors:
    print(f"Great choice! You selected {user_input}.")
else:
    print(f"Sorry, {user_input} is not a valid color.")

Here, the in operator checks if the user’s input matches one of the colors in the valid_colors list. If it does, the program moves forward. If not, it tells the user their input is invalid.

Filtering Data in Lists or Dicts

Another real-world use case is filtering data in lists or dictionaries. Sometimes, you might have a collection of data and need to filter out or find specific items based on a condition. The in and not in operators can be really helpful for this.

For example, imagine you have a list of students and their grades, and you want to find out who passed and who failed. You can filter them out by checking for specific grades:

students = {'Alice': 85, 'Bob': 45, 'Charlie': 70, 'Daisy': 95}
passing_grade = 50

# Find students who passed
passed_students = {name: grade for name, grade in students.items() if grade >= passing_grade}

print(passed_students)

If you want to exclude students who failed instead, you can use the not in operator:

failed_students = {name: grade for name, grade in students.items() if grade < passing_grade}
print(failed_students)

In this case, in is checking if the student’s grade is above the passing grade, while not in helps filter out those who failed.

Membership in Nested Structures

Sometimes, your data might be more complicated, like having nested structures—lists inside lists, dictionaries inside lists, or dictionaries inside dictionaries. The in and not in operators can still help, but you might need to be a little more specific about where you’re checking.

Let’s say you have a list of dictionaries where each dictionary represents a user’s information, and you need to check if a specific username exists. Here’s how you might do it:

users = [
    {'username': 'alice', 'age': 25},
    {'username': 'bob', 'age': 30},
    {'username': 'charlie', 'age': 35}
]

username_to_check = 'bob'

# Check if the username exists in any of the dictionaries
user_exists = any(user['username'] == username_to_check for user in users)

print(user_exists)  # Will return True because 'bob' is in the list of dictionaries

Here, we’re using a list comprehension along with in to check each dictionary for a matching username.

For more complex nested structures, like checking if a value is in a list inside a dictionary, you can use loops or list comprehensions in a similar way.

Recap

  • User input validation: Use in to check if user input is valid against a predefined list of options.
  • Filtering data: Use in and not in to filter or find items in a list or dictionary based on a condition.
  • Membership in nested structures: Even in more complex data structures (like lists of dictionaries), you can still use in and not in to check for membership.

These real-world examples show you just how powerful the in and not in operators can be. They’re simple to use but extremely helpful in everyday programming tasks.

Let’s go over some common mistakes people make when using the in and not in operators. These mistakes can trip you up, especially when you’re just starting to use them. Don’t worry, though! I’ll walk you through these mistakes so you can avoid them in your own code.

Watch Out for These Common Mistakes

Comparing Numbers Across Data Types (int vs. float)

One mistake that often happens when using in is comparing different data types. For example, mixing integers (int) with floating-point numbers (float) can lead to unexpected results.

Consider this example:

number = 5
numbers_list = [5.0, 3.2, 4.1]

if number in numbers_list:
    print("Found!")
else:
    print("Not found!")

At first glance, you might think the result would be “Found!” since 5 is in the list. But here’s the problem: 5 is an integer, and 5.0 in the list is a float. In Python, 5 and 5.0 are not considered the same because they are different data types. So, the output here will actually be “Not found!”.

To avoid this, make sure you’re comparing the same data types. If you’re dealing with a list of floats, convert your integer to a float (or vice versa) before checking membership.

number = 5.0  # Make sure both are floats
numbers_list = [5.0, 3.2, 4.1]

if number in numbers_list:
    print("Found!")
else:
    print("Not found!")

Now, the output will be “Found!” because both values are floats.

Membership Doesn’t Work Like Search (Substring vs. Sequence)

Another mistake is expecting the in operator to work like a search in a string or list. The in operator checks for membership, which means it checks if an element is exactly in a collection. But it doesn’t work like a search for substrings in strings or sequences in lists unless you’re looking for an exact match.

Take this example:

sentence = "Hello, how are you?"
if 'how' in sentence:
    print("Found!")
else:
    print("Not found!")

At first, you might think this will print “Found!” because the word ‘how’ appears in the sentence. And guess what? It does! But keep in mind that in is checking if the substring ‘how’ is present exactly as is, not whether the words are part of a sentence. If you’re dealing with lists or tuples, it will check for the presence of exact elements within them, not part of a sequence.

But what if you do something like this with a list of numbers?

numbers = [1, 22, 33, 44, 55]
if 2 in numbers:
    print("Found!")
else:
    print("Not found!")

This checks if 2 is exactly in the list, but 2 isn’t in the list. The in operator doesn’t search through the list for the digits or parts of numbers, so it returns “Not found!”

So remember: the in operator checks for exact membership—whether a value exists in the sequence, not part of it.

Case-Sensitive Matching in Strings

One thing that can be frustrating when working with strings is that the in operator is case-sensitive. That means "apple" and "Apple" are treated as different strings.

For example:

fruit = "apple"
if "Apple" in fruit:
    print("Found!")
else:
    print("Not found!")

This will print “Not found!” because "Apple" (with a capital A) doesn’t exactly match the lowercase "apple". Python treats these as two different strings because it’s case-sensitive.

If you want to make your check case-insensitive, you can either convert both strings to the same case (either lowercase or uppercase):

fruit = "apple"
if "Apple".lower() in fruit.lower():
    print("Found!")
else:
    print("Not found!")

Now, it will print “Found!” regardless of whether you input the word with a capital letter or not.

Recap

  • Comparing Numbers Across Data Types: When checking membership between different data types, like int and float, make sure the types match.
  • Membership Doesn’t Work Like Search: The in operator checks for exact matches, not substrings or parts of sequences.
  • Case-Sensitive Matching: The in operator is case-sensitive, so you need to handle cases where capitalization matters, or use methods to normalize the case.

By being aware of these common mistakes, you’ll be able to use the in and not in operators more effectively.

Conclusion

And that’s a wrap! Now that you’ve learned about the in and not in operators in Python, you should feel confident using them in your code. Whether you’re checking for membership in strings, lists, dictionaries, or more complex structures like sets, these operators are simple but powerful tools for everyday coding tasks.

To quickly recap:

  • in helps you check if an item exists within a collection.
  • not in does the opposite by checking if an item doesn’t exist.
  • You can use these operators in many real-world scenarios, like user input validation, filtering data, and working with nested structures.
  • But don’t forget to watch out for some common mistakes, like comparing different data types or thinking that in works like a search function for substrings.

With these tips in mind, you’ll be able to use these operators smoothly and avoid the most common pitfalls. Keep practicing, and soon, they’ll feel second nature!

If you have any questions or want to explore more examples, feel free to reach out or leave a comment.

Bonus: Python Membership Operator Cheat Sheet

Data Typein Examplenot in Example
String"Py" in "Python" → True"Go" not in "Python" → True
List3 in [1,2,3] → True5 not in [1,2,3] → True
Tuple1 in (1,2,3) → True4 not in (1,2,3) → True
Set2 in {2,3,4} → True1 not in {2,3,4} → True
Dictionary1 in {1: "a"} → True"a" not in {1: "a"} → True

Interactive Skill Test: Are You Ready to Master Membership Operators?

Now that you’ve learned about in and not in, let’s test your understanding with a little interactive quiz! Try to answer the following questions based on what you’ve learned. Don’t worry if you’re unsure—this is just for fun and to help you practice.

1. Basic Membership Check
What will be the result of the following code?

colors = [‘red’, ‘green’, ‘blue’]
if ‘green’ in colors:
print(“Found!”)
else:
print(“Not found!”)

A) Found!
B) Not found!
C) Error

A) Found! – ‘green’ is in the list of colors.

2. Membership in Strings
What will be the result of this code?

sentence = “Python is awesome”
if ‘is’ in sentence:
print(“Found!”)
else:
print(“Not found!”)

A) Found!
B) Not found!
C) Error

A) Found! – ‘is’ is a substring of the string.

3. Case-Sensitive Membership
What will the following code print?

fruit = “apple”
if “Apple” in fruit:
print(“Found!”)
else:
print(“Not found!”)

A) Found!
B) Not found!
C) Error

B) Not found! – The membership check is case-sensitive, and ‘Apple’ does not match ‘apple’.

4. Membership in Lists of Numbers
What will happen when you run this code?

numbers = [1, 22, 33, 44, 55]
if 2 in numbers:
print(“Found!”)
else:
print(“Not found!”)

A) Found!
B) Not found!
C) Error

B) Not found! – The number 2 is not in the list.

5. Using not in
What is the output of this code?

animals = [‘dog’, ‘cat’, ‘rabbit’]
if ‘fish’ not in animals:
print(“Not found!”)
else:
print(“Found!”)

A) Not found!
B) Found!
C) Error

A) Not found! – ‘fish’ is not in the list of animals.

6. not in with Strings
What will the following code print?

sentence = “I love Python programming”
if ‘Java’ not in sentence:
print(“Not found!”)
else:
print(“Found!”)

A) Not found!
B) Found!
C) Error

A) Not found! – ‘Java’ is not in the sentence, so not in returns True.

External Resources to Enhance Your Learning

To deepen your understanding of membership operators in Python and explore other related concepts, here are some great resources you can check out:

Python Official Documentation on Membership Operators
Dive into the official Python documentation for a detailed explanation of the in and not in operators, their syntax, and use cases.

Python Tutor – Visualizing Python Code
Sometimes it helps to visualize how the in and not in operators work under the hood. Python Tutor allows you to step through your code visually, which can help you understand what’s going on.

About The Author

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Rating