Python’s list comprehensions are great, but I’ve found a new (to me) use of them: iterating over a list and returning the first match when there might be multiple possible matches. (To be more accurate, my solution uses a generator expression rather than a list comprehension)
In other words, I’m emulating a break statement in the loop, but only for the first match. In code, that is:
1 2 3 4 5 | val = None for x in some_list: if match(x): val = x break |
I could do this with a list comprension and getting the element at index 0:
1 | val = [x for x in some_list if match(x)][0] |
…but that means the whole list is created, and what if the list is large and/or the match() function is expensive? I’d really like to just stop looping when I’ve got a match. Generator expressions come in handy here:
1 | val = (x for x in some_list if match(x)).next() |
Also note that in Python3, functions like filter() return an iterator (which may have a generator under the hood, I’m not sure), so this is possible:
1 | val = next(filter(match, some_list)) |
Now I’ve got the first matching value, and I don’t have to match against every item in the list. Hooray for functional Python