Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 994
Anton Shevtsov Avatar asked Oct 04 '13 05:10

Anton Shevtsov


2 Answers

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.

like image 141
Tim Pietzcker Avatar answered Oct 23 '22 06:10

Tim Pietzcker


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.

like image 2
Tim Peters Avatar answered Oct 23 '22 07:10

Tim Peters