if i+1 is non existing value then stopn the loop and value of i+1 where i is end of list should not execute.
my_list = [1,2,3,4,5]
for i in range(len(my_list)):
if my_list[i] == my_list[i+1]:
print('ok')
#IndexError: list index out of range
if i+1 is non existing value then stopn the loop and value of i+1 where i is end of list should not execute.
my_list = [1,2,3,4,5]
for i in range(len(my_list)):
if my_list[i] == my_list[i+1]:
print('ok')
#IndexError: list index out of range
Try this,
my_list = [1, 2, 3, 4, 5]
for i in range(len(my_list) - 1):
if my_list[i] == my_list[i+1]:
print('ok')
Error occurs because my_list[i+1]
tries to access 6th element of list containing 5 elements.
Not sure what is your goal here, but this is possible fix - since you are comparing current and next element all the time, you can loop from first to 5th element:
my_list = [1,2,3,4,5]
for i in range(len(my_list) - 1):
if my_list[i] == my_list[i+1]:
print('ok')
my_list = [1,2,3,4,5]
for i in range(len(my_list)-1):
if my_list[i] == my_list[i+1]:
print('ok')
If the length of the list is n we have elements from 0 to n-1 only since list indices start from 0.
#hope this code helps you
my_list = [1,2,3,4,5]
for i in range(len(my_list)):
if i in my_list:
print("ok")
i = i +1