Thursday, September 4, 2014

Python Idiom: First Occurence

Finding the first occurrence in a collection of data is a common problem. 
 

# Non Idiomatic
found_line = None
for line in logfile:
   if regex.match(line):
      found_line = line
      break
return found_line

Compared to

# Idiomatic
return next(line for line in logfile if regex.match(line), None)


or

# Idiomatic (thanks to Suresh V)
from itertools import dropwhile
return next(dropwhile(lambda x: not regex.match(x), logfile), None)


The idiomatic solution is not only more compact, but it reads better.

§