Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

puzzling python index error

Here is a piece of python code ("result" is a nested list created before)

for i in range(len(result)-1):
    try:
        result[i][3]=0
        result[i+i][0]=0
    except IndexError:
        print "fail", result[i][3], result[i+1][0], i, len(result)
return result

which, to my astonishment, quite often prints "fail" (with non-revealing values for i, len(result), e.g. 24, 31). How can

result[i][3]=0
result[i+i][0]=0

produce the IndexError exception, if

print result[i][3], result[i+1][0]

does not?

like image 377
user8268 Avatar asked Aug 10 '26 16:08

user8268


1 Answers

You are accessing the index i + i, not i + 1:

result[i+i][0]=0

This means that by the time you reach i // 2 + 1 you have an index error, whatever the size of your list.

like image 93
Martijn Pieters Avatar answered Aug 12 '26 11:08

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!