why any( ) instead of firsttrue( ) ?

Tim Chase python.list at tim.thechases.com
Tue Jun 8 20:49:50 EDT 2010


On 06/08/2010 06:18 PM, MRAB wrote:
> danieldelay wrote:
>> firsttrue(line.strip() for line in '\n\n \n CHEERS  \n'.split('\n'))
>>
> Should 'firsttrue' return None? Surely, if none are true then it should
> raise an exception.

which can fairly elegantly be written with stock-Python as

#  try:
     result = itertools.ifilter(None,(
       # some arbitrary generator goes here
       line.strip()
       for line in
       '\n\n \n CHEERS  \n'.split('\n')
       )).next()
#  except StopIteration:
#    result = YOUR_DEFAULT_HERE

-tkc









More information about the Python-list mailing list