Python “in” and “not in”: Explained Using 8 Examples!

In this article let us learn about the “in” and “not in” operators in Python.

The first step in the journey towards mastery of any programming language is to learn about the various operators provided by that language and learn how to wield them. Python is no exception to this rule!

Every programming language comes in-built with

  • arithmetic operators for addition, subtraction, multiplication and division operations, and
  • logical operators for AND, OR, NOT and XOR operations.

But since Python is a language that focuses on readability we have more operators than the usual ones which programmers can benefit from. Two good examples of such operators are the “in” and “not in” operators.

Even though the concepts might look simple, our brains are really good at understanding the concepts but not so good at remembering them!

The best trick to make our brains remember stuff is via active learning. By “active learning” I mean “doing”!!

So put on your coding hats, open your laptops and start experimenting and playing with the code shown in the examples as you read them!

The phrase “Practice Makes Perfect” did not survive so many centuries for no reason!

For those of you who came here just to refresh your memories, here is a Cheatsheet!

Python “in” and “not in” Operators: Cheatsheet

The table below shows the meaning and usage of the “in” and “not in” operators

OperatorMeaningExample
inis a member of>>> list1 = [1, 2 , 3]
>>> 3 in list1
True
>>> 5 in list1
False
not inis not a member of>>> list1 = [1, 2 , 3]
>>> 5 not in list1
True
>>> 3 not in list1
False
Cheatsheet: “in” and “not in” operators

What does “in” in Python do? The “in” operator is used to verify that an object is a member of the given container.

What does “not in” in Python do? The “not in” operator is used to verify that an object is not a member of the given container

Essentially the “not in” operator does the opposite of what the “in” operator does.

If the words “objects” and “containers” in the paragraphs and table above are causing more confusion than explanation, then you are not alone! If it does I suggest you skip to the next section of the article which discusses the fundamentals!

The outputs are bolded in the Example column (column 3) above.

Since these 2 operators are checking the membership of the given object these are also called membership operators.

The answers above are aimed at those people who are familiar with those terms as those terms are common across many programming languages.

This article is specifically crafted keeping beginners in mind, so if you are feeling confused, forget that you ever read the paragraphs above, find a quiet place, focus for the next 10 to 15 minutes and read the rest of the article, then come back and read the answers above, I guarantee they will make more sense!

Let us start this article by learning about “Classes”, “Objects” and “Containers” in Python!

Fundamentals Needed Before You Can Learn The “in” And “not in” Operators

Classes and Objects

Let us not take the academic approach and start this section off with a nice definition of objects. Instead, let us have a look at some examples to try and develop an intuitive feel for them!

Dog

If you are wondering What is the picture of a dog doing in an article like this? It is not there by mistake, it has been put there by design!

If someone asks you what animal is there in the pic above? you would say “dog

How did your brain know that the above picture is a “dog” and not “something else”?

Because the animal in the picture above matches all the characteristics of what we humans call a “dog”!

Hence we can say, a dog is an animal that has some characteristics of X, Y, and Z. Here X, Y, and Z can be a long snout, nose, etc!

In more formal words,

A dog is a class of pet characterized by X, Y and Z.

Now have a look at the next picture.

In the pic above we have a group of pets, each pet in the picture also match the characteristic of a dog, hence we can say that there are 3 pets of the type “dogin the above picture.

Let us have a look at another example.

In the pic above we can see a bunch of cool devices from the future which we can classify as “Robots”. In other words,

These are electronic devices belonging to the “Robots” class

Each individual robot/device itself is an object

In computer languages, no matter whether we are looking at a robot or a dog (or a robot dog!) we call each individual item as an “object” belonging to a particular “class”

Objects: The tangible individual item

Class: The “Idea

Let us have a look at another picture just to make the concept of objects familiar

Class and objects example picture

In the pic above, we have 3 pets belonging to the class “Dogs”. Each pet is an individual object and collectively they all can be classified under the “Dogs” class.

In other words, Coco, Buster, and Buddy are objects belonging to the class “Dogs”

Objects: The tangible individual item: Coco, Buster, and Buddy

Class: The “Idea: A dog is a class of pet characterized by X, Y and Z.

Let us have a look at one last example

Here on the left, we have a few apartments and on the right, we have a blueprint. Let’s call this Blueprint-A.

Each of the individual apartments is built using the same blueprint. Hence each individual apartment is an object belonging to the class “Blueprint-A”

Objects: The tangible individual item: Apartments 1, 2, 3, 4

Class: The “Idea: Blueprint-A

This is a “hard to grasp” concept, but once you understand the idea behind it, you will never forget the concept!

If you are feeling confused, sit quietly for a moment and think about the examples I gave till the “Aha!” moment comes to you!

Once you are ready, read on!

Okay, let us open the Python interpreter and do some coding!

>>> x = 10
>>> a = "apple"
>>> list1 = [1, 2, 3]

Here we have created 3 variables.

  • The variable x holds the integer value 10
  • The variable a holds the string “apple” and
  • The variable list1 holds the list [1, 2, 3]

In the world of python whatever is held by a variable name is an “object”. In Example#1 above, 10 is an integer object, “apple” is a string object, and [1, 2, 3] is a list object.

You can see “what type an object is” using the aptly named built-in function “type()” as shown in Example#2 below.

>>> type("apple")
<class 'str'>
>>> type(10)
<class 'int'>

As you can see the integer 10 is of type int, short for “integer” and the word “apple” is of type str short for “string”.

Containers in Python

Consider a “list” as shown in the image below.

Container Example#1: List

The list can be a grocery list, a to-do list, or anything else. In essence

A list is used to group related items put together so that we can access them efficiently in a nicer format.

Imagine going to the grocery shop with a bunch of papers in hand, each paper containing a single item to buy. Using a list like that would be very inefficient as compared to a single paper containing all the items we wish to buy!

Hence list can be thought of as a container of related items!

In the programming world, half the job revolves around efficiently organizing the data so that we can process them easily.

The list is not the only container available in Python. Sometimes using a “list” datatype makes sense, other times some other type of container may be more useful.

For example, if we want to store pairs of related items, a better way to store that is to use a dict container. “Dict” short for “Dictionary” come from the real-world dictionary which contains a pair of items (the word and the meaning) for each entry.

Container Example#2: Dictionary

Containers are data structures that are used to hold objects.
Examples of containers include built-in types like lists, tuples, sets, and dicts, and several more from the collections module.

Sidenote
Built-in types are the ones you can use in your programs without an “import” statement
“Collections” is a module that comes with the standard library, they are more like booster packs to give our programs some superpowers, like Neo learned kungfu by loading a program, we can import some modules and make use of all its functions!

Side-Sidenote!
“Standard library” is a group of modules that come with the standard python installation. If you need something more there are several thousand packages which you can install and make use of!

Now that we have learned all the prerequisites needed, let us get back to the main focus of this article!

The “in” operator

Let us start with an example.

>>> list1 = [1, 2, 3, 4, 5]
>>> 3 in list1
True
>>> 6 in list1
False

Here

  • In line#1 we have created a simple list container called list1 with numbers 1 through 5
  • In line#2 we are checking if object “3” is present inside the container “list1” and the output says True
  • In line#4 we are checking if object “6” is a member of the container “list1” and we get False

Both the check’s for membership have been achieved using the “in” operator.

Hence as we saw in the cheatsheet near the beginning of the article

The “in” operator is used to verify that an object is a member of the given container.

The “not in” operator

Let us continue our previous example.

>>> a = [1, 2, 3, 4, 5]
>>> 3 in a
True
>>> 6 in a
False
>>> 6 not in a
True
>>> 2 not in a
False

Here

  • In line#6 we are checking if the object “6” is not a member of the container list1 and the output says True.
  • In line#8 we are checking if object “2” is not a member of the container list1 and the output says False, since 2 is present in the list [1, 2, 3, 4, 5]

Both the check’s for “non-membership” have been achieved using the “not in” operator.

Hence as we saw in the cheatsheet near the beginning of the article

The “not in” operator is used to verify that an object is not a member of the given container

Now that we have learned what these operators do, next let us learn how to use them in our programs!

When and Where To Use “in” And “not in” Operators?

Okay, the above examples are a bit abstract, they are good for explaining the concepts but are not good enough to be used practically in our programs!
Let us learn the “how”, “when”, and “where” these membership operators can be utilized practically in our programs!

A good time to use the “in” operator

A typical situation where we need the “in” operator is whenever you need to

Finding needle in a haystack

For example, consider you are creating a program that tells you which universe a given superhero belongs to, the DC universe or the Marvel universe.

This program can utilize the “in” membership operator as shown below.

DC_universe_heroes = [ "Superman",
                        "Batman",
                        "Wonder Woman",
                        "Aqua man"]

Marvel_universe_heroes = ["Ironman",
                          "Captain America",
                          "Thor",
                          "Hulk"]

hero = input("Please enter your favorite superhero: ")

if hero in DC_universe_heroes:
  print(f"{hero} is a part of the DC Universe!")
elif hero in Marvel_universe_heroes:
  print(f"{hero} is a part of the Marvel Universe!")
else:
  print(f"{hero} is not a part of the DC or Marvel universes!")

Before I explain what the code does, take a minute or 2 to understand what is going on. Open your code editor and try out the example yourself before you look at the explanation!

No great programmer has achieved greatness just by reading!

So, GO DO SOME CODING!

Running the code above will give an output like this

Please enter your favorite superhero: Ironman
Ironman is a part of the Marvel Universe!

Please enter your favorite superhero: Superman
Superman is a part of the DC Universe!

Please enter your favorite superhero: Popeye
Popeye is not a part of the DC or Marvel universes!

This is again a fun example, in the real world if you have gazillion lines of log data to sort through and you are looking for a particular string in that file you can do so as follows.

For example, say you own a DVD store, and you have a bunch of movies and albums on your shelves.

One fine day, a customer comes in and asks for a rare album. You can’t simply search the whole store, as this is a classic “Find a needle in a Haystack” kind of situation. As long as you maintain a database of all the albums you do have, you can write a short program like this.

album_needed = "some cool album"

# open the file and read all the lines into lines list
file = open("albums_database.txt")
linesList = file.readlines()
if album_needed in linesList:
      print("Yes we do have your album!")
else:
      print("Sorry, the album you requested is not available :(")

Here

  • In line-1, the name of the album is stored into the variable album_needed
  • Line-4 opens the file and line-5 reads all the lines into a list container called linesList
  • line-7 is where the magic happens, with a single line of code, we search through the entire “haystack” to find our “needle” with the help of our new favorite “in” operator
  • Then we tell the user if the album was found or not.

A good time to use the “not in” operator

The “not in” operator is basically the inverse of the “in” operator.
This is especially useful when we are looking for the absence of something!

Consider a situation, we have just run a software test, and now have a gazillion lines of logs

We are looking for the absence of the word “error” in our code so that we can say that the software has passed the test.

This is a good example where we can use the “not in” operator instead of the “in” operator since our interest is in finding the absence of the line “error

# open the log file and read all the lines into lines list
file = open(log.txt)
linesList = file.readlines()
if "error\n" not in linesList:
      print("Hurray! your code is bug free!")
else:
      print("There is a bug in your code :(")

Here

  • In line-2, we open the log file
  • In line-3 we read all the lines in the log into a list of strings called linesList
  • Line-4 is where the magic happens, using our “not in” operator we conveniently verify if the string “error occurred” is in the list or not and we print out if the software has passed or failed the test.

Another example is in getting user passwords while registering. Imagine you have a password field, and you would like the user to enter a strong password, and you need some

  • lower-case,
  • upper-case,
  • numbers and
  • special characters

as a requirement.

Then you can easily check the entered password, by converting it into a list of characters and checking the password for strength using the “not in” operator, and rejecting the entered password if the requirements are not fulfilled!

I leave it to you as a challenge to try this one out on your own!
Might take a few hours, but hey, is there anything more fun than hacking and solving puzzles with Python!

I understand that in a corner of your mind, you are thinking that we could have achieved the same results in Example#7 using the “in” operator instead of the “not in” operator.

What is the reason behind our choice? Always remember the core idea behind Python

A code once written is read a thousand times!

In other words, “Readability” is very important.

Good readable code usually has a very long life in the industry. Bad unreadable code usually gets rewritten, which means doing the same thing 2 times, which means a waste of time and money!

Do it right or do it twice!

I know that throughout this article I have been praising the “in” and “not in” operators a lot, you might be thinking they are special enough to deserve this much praising!

To justify my praising, and to satiate your curiosity, let us next learn how these operators work under the hood.

How are the “in” and “not in” operators implemented under the hood?

In a world without the “in” and “not in” operators, our superhero example would have been written like this

DC_universe_heroes = [ "Superman",
                        "Batman",
                        "Wonder Woman",
                        "Aqua man"]

Marvel_universe_heroes = ["Ironman",
                          "Captain America",
                          "Thor",
                          "Hulk"]

hero = input("Please enter your favorite superhero: ")

# Variable to keep track of whether the mission of finding the hero is accomplished or not
mission_accomplished = False

for DC_hero in DC_universe_heroes:
  if hero == DC_hero:
    print(f"{hero} is a part of the DC Universe!")
    mission_accomplished = True

if mission_accomplished == False: # check to make sure that hero is not found
  for Marvel_hero in Marvel_universe_heroes:
    if hero == Marvel_hero:
      print(f"{hero} is a part of the Marvel Universe!")
      mission_accomplished = True

if mission_accomplished == False: # not found in both lists
  print(f"{hero} is not a part of the DC or Marvel universes!")

A Challenge for you!

I want to challenge you to try and understand what the code does!

These thinking exercises will condition your brain to think like a programmer!

The basic idea used here is to iterate through the entire haystack, one strand at a time checking each item along the way to see if that item is a hay strand or the needle and then giving up either when the needle is found or when the last hay strand is checked.

But the point I am trying to make here is, see how complicated the entire code became if we chose not to use the membership operators, this is what made me appreciate these membership operators so much throughout this article!

This sort of membership checking is something that we need to do regularly and complicated code is a maintenance nightmare and hence should be avoided at all costs!

I love the fact that Python provides us with their super cool operators, which in turn saves our time and lets us focus on the bigger problems!

Whenever you get confused between whether to use “in” or “not in”, remember

Readability! Readability! Readability!

Where To Go From Here?

If you have made it this far, then “Bravo!” to you! I admire your spirit and hunger for knowledge!

I suggest you play around with these operators till they become second nature. This entire article used only the list containers. Try using these membership operators with other containers like dicts and sets.

Then go ahead and try reading the cheat sheet at the beginning of the article again, I am sure this time it will make sense!

Once you have mastered these membership operators, go ahead and check out the “Related Articles” section below for more articles!

I hope you found this article useful!

Feel free to share this article with your friends and colleagues!

Related articles

Python Comparison Operators Explained Using 10 Examples!

Python “is” and “is not”: Explained Using 8 Examples!

Python: “is” vs “==” Similarities and Differences

Python: “is not” vs “!=” Similarities and Differences

Python’s ‘==’ Operator: Meaning and Usage Explained with Examples

Python’s ‘!=’ Operator: Meaning and Usage Explained with Examples

References

Python.org: Operators

Python.org: Expressions

Python.org: Collections

4 thoughts on “Python “in” and “not in”: Explained Using 8 Examples!”

Comments are closed.