[Tutor] checking for a condition across a list

Walter Vannini walterv@jps.net
Sun, 13 May 2001 20:20:22 -0700


Let the original code be:

myList = [1, 0, 1, 0, 0, 1, 1]
#if myList[0] == myList[1] == ... == myList[6] == 1:
if myList[0] == myList[1] == myList[2] == myList[3] == myList[4] == \
        myList[5] == myList[6] == 1:
    print "They're all ones!"
else:
    print "They're not all ones!"

One possible replacement is:

myList = [1, 0, 1, 0, 0, 1, 1]
if reduce(lambda x,y: x and y, map(lambda x: x==1, myList) ):
    print "They're all ones!"
else:
    print "They're not all ones!"

or, as a minor variation:

myList = [1, 0, 1, 0, 0, 1, 1]
def theCondition(x):
    return x==1
if reduce(lambda x,y: x and y, map(theCondition, myList) ):
    print "They're all ones!"
else:
    print "They're not all ones!"

These are not as efficient as the original,
since there is no short circuiting.
If you want that, a loop with a break is the only thing
I can think of.

Walter

Pijus Virketis wrote:
> 
> Hi,
> 
> I know I posted this question already, but the list has been very busy, so
> I hope it's not too obnoxious if I bring it up again ... Hopefully, there
> is an obvious way I am missing. Here goes. 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!"
> 
> Thank you!
> 
> Pijus
> ----------------------------------------------------------------------------
> -------------------
> Please have a look at my weblog at www.fas.harvard.edu/~virketis.