The following are 3 alternatives, with benchmarks.
Using next()
The one-liner:
values = list(range(1, 10000000))
value = next((x for x in values if x > 9999999), None)
Using a function
This is an alternative to using next()
using a function, it's about 2%-5% faster:
values = list(range(1, 10000000))
def first_valuefirst(items):
for item in items:
if item > 9999999: # Your condition
return item
return None # Default value
value = first_valuefirst(values)
Using lambda
This is a function that can be used for replacing next()
in all cases. Performance are about 300% slower:
values = list(range(1, 10000000))
def first(items, condition, default = None):
for item in items:
if condition(item):
return item
return default
value = first(values, lambda x: x > 9999999, None)
Benchmarks
- Function: 1x
- Next: 1.02x-1.05x
- Lambda: > 3x
Memory consumption is on par.