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

python— editable, runs on the server

<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

python— editable, runs on the server

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.