Check If Something Is (not) In A List In Python

To check if an element is in a list in Python, you can use the ‘in’ operator. Here’s an example:

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

# Check if 3 is in the list
if 3 in my_list:
    print("3 is in the list")
else:
    print("3 is not in the list")

# Check if 6 is not in the list
if 6 not in my_list:
    print("6 is not in the list")
else:
    print("6 is in the list")

Output:

3 is in the list
6 is not in the list

Alternatively, you can use the in operator in an expression to get a Boolean result. Here’s how you can do it:

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

# Check if 3 is in the list
is_in_list = 3 in my_list
print(f"Is 3 in the list? {is_in_list}")

# Check if 6 is not in the list
is_not_in_list = 6 not in my_list
print(f"Is 6 not in the list? {is_not_in_list}")

Output:

Is 3 in the list? True
Is 6 not in the list? True

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!