Michael Wayne Goodman

Computational Linguist

Python one-liner: Getting only the first match in a list comprehension

2013 January 30

Using next() with a generator expression to simulate a break statement in a for-loop. Something like this:

val = next((x for x in some_list if match(x)), default_val)

...which is the same as:

val = default_val
for x in some_list:
    if match(x):
        val = x
        break

Commenter Emanuel Hoogeveen suggested the default_val, because otherwise the next() would raise a StopIteration if there were no matches in the list. He found the answer here on StackOverflow.

And thanks to @ashleyconnor for finding a bug in my code and submitting a pull request!