Here’s the pattern I use:
mylist = [10, 2, 20, 5, 50]
found = next(i for i in mylist if predicate(i))
Or, in Python 2.4/2.5, next()
is a not a builtin:
found = (i for i in mylist if predicate(i)).next()
Do note that next()
raises StopIteration
if no element was found. In most cases, that’s probably good. You asked for the first element, no such element exists, and so the program probably cannot continue.
If, on the other hand, you do know what to do in that case, you can supply a default to next():
conf_files = ['~/.foorc', '/etc/foorc']
conf_file = next((f for f in conf_files if os.path.exists(f)),
'/usr/lib/share/foo.defaults')