Check if all values of iterable are zero Check if all values of iterable are zero python python

Check if all values of iterable are zero


Use generators rather than lists in cases like that:

all(v == 0 for v in values)

Edit:

all is standard Python built-in. If you want to be efficient Python programmer you should know probably more than half of them (http://docs.python.org/library/functions.html). Arguing that alltrue is better name than all is like arguing that C while should be call whiletrue. Is subjective, but i think that most of the people prefer shorter names for built-ins. This is because you should know what they do anyway, and you have to type them a lot.

Using generators is better than using numpy because generators have more elegant syntax. numpy may be faster, but you will benefit only in rare cases (generators like showed are fast, you will benefit only if this code is bottleneck in your program).

You probably can't expect nothing more descriptive from Python.

PS. Here is code if you do this in memcpm style (I like all version more, but maybe you will like this one):

list(l) == [0] * len(l)


If you know that the iterable will contain only integers then you can just do this:

if not any(values):    # etc...


If values is a numpy array you can write

import numpy as npvalues = np.array((0, 0, 0, 0, 0))all(values == 0)