Check if a list contains a False value in Python

avatar

Borislav Hadzhiev

Last updated: Aug 12, 2022

banner

Photo from Unsplash

Check if a list contains a False value in Python #

Use the in operator to check if a list contains a False value, e.g. if False in my_list:. The in operator will return True if at least one False value is contained in the list.

main.py
my_list = [True, True, True, False] if False in my_list: # 👇️ this runs print('The list contains at least one False value') else: print('The list does NOT contain any False values') # 👇️ True print(False in my_list)

We used the in operator to check if a list contains any False values.

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise it evaluates to False.

main.py
my_list = [True, True, True, False] print('hello' in my_list) # 👉️ False print(False in my_list) # 👉️ True

Alternatively, you can use the any() function.

Use the any() function to check if a list contains a False value, e.g. if any(item is False for item in my_list):. The any() function will return True if the list contains at least one False value.

main.py
my_list = [True, True, True, False] if any(item is False for item in my_list): # 👇️ this runs print('The list contains at least one False value') else: print('The list does NOT contain any False values') # 👇️ True print(any(item is False for item in my_list))

We used a generator expression to iterate over the list.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current list item is equal to False.

The any function takes an iterable as an argument and returns True if any element in the iterable is truthy.

If the any() function encounters a False value, it will short-circuit returning True.

If the iterable is empty or none of the elements in the iterable are truthy, the any function returns False.

main.py
my_list = [True, True, True] if any(item is False for item in my_list): print('The list contains at least one False value') else: # 👇️ this runs print('The list does NOT contain any False values') # 👇️ False print(any(item is False for item in my_list))

None of the items in the list is equal to False, so the condition is never met and the else block runs.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.