Hello all!
Do you have any idea why I have this error of ‘index out of range’. Could you please help me how to solve it. When I try len(x)-1 it works but I loose the last element of the list.
Thanks a lot in advance!
Hello all!
Do you have any idea why I have this error of ‘index out of range’. Could you please help me how to solve it. When I try len(x)-1 it works but I loose the last element of the list.
Thanks a lot in advance!
you’re accessing x[i+1]. If your range is from 0,len(x), and x has 5 items, it will try to get the 6th item, which doesn’t exist.
Ohh I see. You are right .Thanks a lot. Any idea how I can solve this ?
That depends on what you’re wanting to do. You’re asking Python to access an item that doesn’t exist, so you’d solve this by not asking for that non-existent item. If you share your file and let us know what you’re trying to do I’m sure someone will help.
one solution might be to evaluate the current element x[i] in relation to the previous element x[i-1] (instead of the next element x[i+1] ) because x[i-1] is always reacheable
for i in range(1, len(x)):
#compare each element in x with previous one
#start from the second element of x
if x[i] - x[i-1] == 1:
z = x[i]
else:
z = x[i-1]
a.append(z)