views:

110

answers:

3

Is there a good, succinct/built-in way to see if all the values in an iterable are zeros? Right now I am using all() with a little list comprehension, but (to me) it seems like there should be a more expressive method. I'd view this as somewhat equivalent to a memcmp() in C.

values = (0, 0, 0, 0, 0)
# Test if all items in values tuple are zero
if all([ v == 0 for v in values ]) :
    print 'indeed they are'

I would expect a built-in function that does something like:

def allcmp(iter, value) :
    for item in iter :
        if item != value :
            return False
    return True

Does that function exist in python and I'm just blind, or should I just stick with my original version?

Update

I'm not suggesting that allcmp() is the solution. It is an example of what I think might be more meaningful. This isn't the place where I would suggest new built-ins for Python.

In my opinion, all() isn't that meaningful. It doesn't express what "all" is checking for. You could assume that all() takes an iterable, but it doesn't express what the function is looking for (an iterable of bools that tests all of them for True). What I'm asking for is some function like my allcmp() that takes two parameters: an iterable and a comparison value. I'm asking if there is a built-in function that does something similar to my made up allcmp().

I called mine allcmp() because of my C background and memcmp(), the name of my made up function is irrelevant here.

+4  A: 

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

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

This works because all integers are treated as true except zero.

Mark Byers
That is shorter, but I think it conceals the meaning behind what it does even more since it depends on values being `== 0`.
mjschultz
-1 By the time you have heavily commented the code so that it can be understood by non-sophists, you might as well have written 'all(v == 0 for v in values)` which is self-explanatory and future proof (when you decide that it should have been some integer other than zero).
John Machin
+8  A: 

Use generators rather than lists in cases like that:

all(v == 0 for v in values)
Tomasz Wysocki
Interesting, I was unaware of generators, thanks for that tidbit.
mjschultz
+1  A: 

If values is a numpy array you can write

import numpy as np
values = np.array((0, 0, 0, 0, 0))
all(values == 0)
gnibbler
That `all` line is precisely as expressive and meaningful as I want. I just wish it didn't rely on numpy. :(
mjschultz