Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to check if something is in a list Python

Understanding Python Lists

Before we delve into how we can check if something is in a list in Python, let's first understand what lists are.

In Python, a list is a data collection type that is ordered and changeable. Think of it as a bag where you can put your things — be it numbers, strings, other lists, or even a combination of all these things. A list in Python is just like that, but instead of physical objects, we store data in it.

Here's an example of a Python list:

my_list = ["apple", "banana", "cherry"]

The 'in' Keyword in Python

The in keyword in Python is a powerful tool that allows us to check if a certain item exists in a list. You can think of it like you're playing 'Hide and Seek', and you're the one who’s "it". You need to find your friends (the items) who are hiding in different places (in a list).

Here's an example of how you can use the in keyword:

my_list = ["apple", "banana", "cherry"]
if "apple" in my_list:
    print("Yes, 'apple' is in the fruits list")

Using the 'in' Keyword in Python

The in keyword in Python is used within a conditional statement, the if statement. The if statement in Python is used to test a specific condition. If the condition is true, then the code under the if statement will be executed.

Let's take an example. Suppose we have a list of numbers, and we want to check if the number 3 is in the list.

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

In this case, because 3 is indeed in the list, our program will print: "Yes, the number 3 is in the list."

Using the 'not in' Keyword in Python

Conversely, Python also allows us to check if an item is not present in the list using the not in keyword. Just like the in keyword, not in is also used within an if statement.

Suppose we have a list of names and we want to check if "John" is not in the list.

names = ["Alice", "Bob", "Charlie"]
if "John" not in names:
    print("No, John is not in the list.")

In this case, because "John" is not in the list, our program will print: "No, John is not in the list."

Conclusion

So, diving into the world of Python lists feels a bit like going on an adventure, doesn't it? You've got your trusty in keyword to help you find hidden treasure (items in the list), and your loyal not in keyword to help you avoid dangerous traps (items not in the list). Much like an adventurer, a good Python programmer knows when to use the right tool for the job.

Remember, coding isn't just about writing lines of code. It's more about solving problems and making things work. Keep practicing and you'll become more and more proficient. So, go forth and explore the vast universe of Python lists with your newfound powers! Happy coding!