-1

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

Shah Vipul
  • 625
  • 7
  • 11

4 Answers4

1

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')
Maran Sowthri
  • 829
  • 6
  • 14
1

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')
svorcan
  • 340
  • 1
  • 11
1
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.

Indexing elements

Swaroop Maddu
  • 4,289
  • 2
  • 26
  • 38
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
Arbaz
  • 11
  • 1
  • 4