Welcome, guest | Sign In | My Account | Store | Cart

Often it is useful to know whether all elements of sequence meet certain criteria, or if only some pass a test. These two functions "every" and "any" do just that.

Example usage:

>>> every(lambda c: c > 5,(6,7,8,9))
1
>>> every(lambda c: c < 5,(6,7,8,9))
0
>>> any(lambda c: c > 5,(6,7,8,9))
1
>>> any(lambda c: c < 5,(6,7,8,9))
0
Python, 21 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
def every (pred, seq):
    """every takes a one argument predicate
    function and a sequence. Returns true
    if every element in seq returns true for
    predicate, else returns false.
    The predicate function should return true or false.
    """
    for i in seq:
        if not pred(i): return 0
    return 1

def any (pred, seq):
    """any takes a one argument predicate
    function and a sequence. Returns true
    if any element in seq returns true for
    predicate, else returns false.
    The predicate function should return true or false.
    """
    for i in seq:
        if pred(i): return 1
    return 0

3 comments

Alex Martelli 20 years, 1 month ago  # | flag

Numeric (aka Numpy) has interesting, fast implementations of these. Also consider:

def every(pred, seq):
    return len(seq)==len(filter(pred,seq))
def any(pred, seq):
    return len(filter(pred,seq))
and/or:
import operator
def every(pred, seq):
    return reduce(operator.and,map(pred,seq))
def any(pred, seq):
    return reduce(operator.or,map(pred,seq))

The functional forms are elegant and fast.

Jørgen Cederberg 19 years, 6 months ago  # | flag

Errors in example. The example usage indicated, produces the wrong (the inverse) output, which I guess is caused by a typo.

Regards

Jorgen Cederberg

Oren Tirosh 19 years, 2 months ago  # | flag

No early bail-out. These versions can be much slower if the evidence is found early in the sequence - they don't bail out immediately like those in the recipe.

Created by Jon Dyte on Thu, 19 Apr 2001 (PSF)
Python recipes (4591)
Jon Dyte's recipes (1)
Python Cookbook Edition 1 (103)

Required Modules

  • (none specified)

Other Information and Tasks