Search code examples
pythonalgorithmwhile-loop

loop from end to start


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?


Solution

  • 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.