W3docs

Fastest way to check if a value exists in a list

The fastest way to check if a value exists in a list is to use the in operator.

The fastest way to check if a value exists in a list is to use the in operator. For example, if you have a list my_list and you want to check if the value x exists in it, you can simply use the following code:

Check if a value exists in a list using in keyword

if x in my_list:
    print("x exists in my_list")
else:
    print("x does not exist in my_list")

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

Another way to check if a value exists in a list is to use the any() function along with a generator expression. For example, the following code will also check if x exists in my_list:

Check if a value exists in a list using any function

if any(x == item for item in my_list):
    print("x exists in my_list")
else:
    print("x does not exist in my_list")

This method is slightly less efficient than using the in operator but is more flexible, you can use any comparison function instead of == and can be useful if you have a more complex comparision to make.