Check if something is (not) in a list in Python

In Python, you can check if an item is in a list using the in keyword. For example:

my_list = [1, 2, 3, 4]

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

This will print "3 is in the list" because the number 3 is in the list.

Watch a course Python - The Practical Guide

Similarly, you can check if an item is not in a list using the not in keyword. For example:

my_list = [1, 2, 3, 4]

if 5 not in my_list:
    print("5 is not in the list")
else:
    print("5 is in the list")

This will print "5 is not in the list" because the number 5 is not in the list.

You can also use any() function with a generator expression to check if any of the elements of the list matches the given criteria, which can be any valid expression, this is useful if you want to check if the list contains a particular string, for example:

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

if any(x == "banana" for x in my_list):
    print("banana is in the list")
else:
    print("banana is not in the list")

This will print "banana is in the list".

Note that these methods will work for lists, tuples, sets, and other iterable objects as well.