Fxs7576 Fxs7576 - 29 days ago 21
Python Question

Python - Finding index of first empty item in a list

I am trying to find the index of the first empty item from the following list:

list_ = [10000.0, 6000.0, nan, nan, nan]


and to show the correct output as an index of:

2


I have been referring to the code from this link but I keep receiving the "StopIteration:" error message. Does anyone have the solution to this?

This is the code that I have so far:

try:
next(i for i, j in enumerate(list_) if j == "nan")
except StopIteration:
pass

Answer

Your check condition is wrong, it tries to find an item equal to string "nan". To check if a float var is nan, use math.isnan(j).