Validate All Items in a Sequence
January 24, 2011 at 07:56 PM | categories: python | View Comments
A co-worker was using all and complained that he couldn't use a lambda so that the default call to bool() would be done over the return of the lambda which would so some complex validation and return True or False.
I thought the obvious solution was to use map with all. Obviously you would replace the lambda call to your own validation method if you had any advanced or complicated checking to do. I think this solution works out pretty well.
>>> all(map(lambda x: x>10, xrange(1,20))) False >>> all(map(lambda x: x>10, xrange(20,30))) True
Update
My original post sucked, thanks to Peter Ward and Michael Foord for the feedback. Here is a way to do the same thing using generator expressions.
all(x > 10 for x in xrange(1, 20)) False all(x > 10 for x in xrange(20, 30)) True