Check if all values in a list are Zero in Python

avatar

Borislav Hadzhiev

Last updated: Aug 12, 2022

banner

Photo from Unsplash

Check if all values in a list are Zero in Python #

Use the all() function to check if all values in a list are zero, e.g. if all(item == 0 for item in my_list):. The all() function will return True if all values in the list are zero and False otherwise.

main.py
my_list = [0, 0, 0] if all(item == 0 for item in my_list): # 👇️ this runs print('All elements in the list are 0') else: print('Not all elements in the list are 0') # 👇️ True print(all(item == 0 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 value is equal to 0 and return the result.

The all() built-in function takes an iterable as an argument and returns True if all elements in the iterable are truthy (or the iterable is empty).

main.py
my_list = [0, 0, 0] # 👇️ True print(all(item == 0 for item in my_list))

If the all() function finds a non-zero value, it will short-circuit returning False.

Note that the all() function returns True for any condition if the passed in iterable is empty.
main.py
my_list = [] if all(item == 0 for item in my_list): # 👇️ this runs print('All elements in the list are 0') else: print('Not all elements in the list are 0') # 👇️ True print(all(item == 0 for item in my_list))

If you consider an empty list one where not all values are 0, check for the list's length.

main.py
my_list = [] if len(my_list) > 0 and all(item == 0 for item in my_list): print('all elements in the list are 0') else: # 👇️ this runs print('Not all elements in the list are 0')
We used the and boolean operator, so for the if block to run, both conditions have to be met.

The list doesn't have a length greater than 0, so the else block runs.

Alternatively, you can use the list.count() method.

To check if all values in a list are zero:

  1. Use the list.count() method to count the 0 values in the list.
  2. If the number of 0 values is equal to the list's length, all values in the list are 0.
main.py
my_list = [0, 0, 0] if my_list.count(0) == len(my_list): # 👇️ this runs print('All values in the list are equal to 0')

The list.count() method takes a value and returns the number of times the provided value appears in the list.

main.py
my_list = [0, 0, 0] print(my_list.count(0)) # 👉️ 3

If the number of 0 values in the list is the same as the list's length, then the list contains only 0 values.

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.