At first, I use python 2 days and have more questions. Below one from them.
I have a list (3297 items), i want find index of first item from end where value != 'nan'
Example: (index, value)
[0] 378.966
[1] 378.967
[2] 378.966
[3] 378.967
....
....
[3295] 777.436
[3296] nan
[3297] nan
if want found item with index - 3295
my code (from end to start, step by step)
i = len(lasarr); #3297
while (i >= 0):
if not math.isnan(lasarr[i]):
method_end=i # i found !
break # than exit from loop
i=i-1 # next iteration
run and get error
Traceback (most recent call last): File "./demo.py", line 37, in <module> if not math.isnan(lasarr[i]): IndexError: index out of bounds
what i do wrong?
You're starting beyond the last item in the list. Consider
>>> l = ["a", "b", "c"]
>>> len(l)
3
>>> l[2]
'c'
List indices are numbered starting with 0
, so l[3]
raises an IndexError
.
i = len(lasarr)-1
fixes this.
Is your code raising IndexError
? It should ;-) lasarr
has 3297 items, lasarr[0]
through lasarr[3296]
inclusive. lasarr[3297]
is not part of the list: that's a position one beyond the end of the list. Start your code like this instead:
i = len(lasarr) - 1
Then i
will index that last element of the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With