Using possibly undefined loop variable 'idx'
13 for (idx, time) in enumerate(times):
14 if time == max_time:
15 break
16 return files[idx]
Description
Using a loop variable (i.e. defined by a for loop or a list comprehension or a generator expression) outside the loop can create subtle bugs, like the variable not being defined if the list was empty. Generally, you should avoid using loop variables outside the loop, or define them early.
Bad practice
for i in items:
if item_name(i) == "coffee":
price = calculate_cost(i)
print(price) # raises `NameError` if `items` is empty
Preferred:
price = None # Define variable outside loop
for i in items:
if item_name(i) == "coffee":
price = calculate_cost(i)
print(price)