For a project I’m working on I am processing lots of deeply nested dict-and-list data structures. Often I find myself doing a lookup that I expect to return a list with a single member. Lookups may fail outright, or simply return zero results, so I could write code like this:
try:
value_I_need = lookup_results[0]
except IndexError:
# handle lookup failure, keep going
But lately I’ve been wondering if it would be more future-proof to write a loop, initially assuming it only happens zero or one times:
value_I_need = None
for value_I_need in lookup_results:
break
if value_I_need is None:
# handle lookup failure, keep going
(I say “future-proof” because I may want to re-write or generalize this code to handle lookups with more than one result in them.) Is there anything inherently unpythonic, wrong or slower about either of these two approaches?
The builtin function
next()does exactly that: