[Tutor] checking for a condition across a list

Tim Peters tutor@python.org
Sun, 13 May 2001 22:24:50 -0400


[Pijus Virketis]
> ...
> Let's say I have a list:
>
> >>>myList = [1, 0, 1, 0, 0, 1, 1]
>
> How can I check for some condition across all the members of a list
> simultaneously? In other words, how do I this say  more neatly:
>
> >>> if myList[0] == myList[1] == ... == myList[6] == 1:
> ...     print "They're all ones!"

The simple and obvious way is just to write a reusable function:

def alltrue(x, pred):
    "Return true iff pred(y) is true for all y in x."
    for y in x:
        if not pred(y):
            return 0
    return 1

Then, e.g.,

>>> def isone(x):
...     return x == 1
...
>>> alltrue(isone, [1,1,1,1])
1
>>> alltrue(isone, [1,1,0,1])
0
>>>

Of course there are *silly* ways to do it too, but you'll be better off
pretending I didn't show these <wink>:

>>> map(lambda x: x == 1, [1,1,1,1]) == [1]*len([1,1,1,1])
1
>>> map(lambda x: x == 1, [1,1,0,1]) == [1]*len([1,1,0,1])
0
>>> reduce(lambda x, y: x and y==1, [1,1,1,1], 1)
1
>>> reduce(lambda x, y: x and y==1, [1,1,0,1], 1)
0
>>> len(filter(lambda x: x==1, [1,1,1,1])) == len([1,1,1,1])
1
>>> len(filter(lambda x: x==1, [1,1,0,1])) == len([1,1,0,1])
0
>>>