One more case I have encountered today, where this would have been a good fit.
l = [0, 0, 0, 0, 1]
trimmed_zeros = list(itertools.dropwhile(operator.not_, l))
Now I need first value in the list with a fallback. Then, if it is lower than 10, I need to take the 2nd with the fallback to 1st if it doesn’t exist. With list.get
:
optimal_unit = trimmed_zeros.get(0, FALLBACK)
if optimal_unit < 10:
optimal_unit = trimmed_zeros.get(1, optimal_unit)
Without it (superfluous length checks):
:
optimal_unit = trimmed_zeros[0] if len(trimmed_zeros) else FALLBACK
if optimal_unit < 10 and len(trimmed_zeros) > 1:
optimal_unit = trimmed_zeros[1]
Or this (creating iterator for 2 values just doesn’t feel right):
it = iter(trimmed_zeros)
optimal_unit = next(it, FALLBACK)
if optimal_unit < 10:
optimal_unit = next(it, optimal_unit)