0

i have just started learning python, my level is 0 , i was just checking 1 program and it gave me error :

IndexError: list index out of range

def array123(nums):
    for i in range(len(nums)):
        if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
            return True
    return False

if __name__=="__main__":
    array123([0, 2, 2,1,2])

IndexError Traceback (most recent call last) in ----> 1 array123([0, 2, 2,1,2])

in array123(nums) 1 def array123(nums): 2 for i in range(len(nums)): ----> 3 if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3: 4 return True 5 return False

IndexError: list index out of range

Please can some one explain me the logic .

PilouPili
  • 2,601
  • 2
  • 17
  • 31

1 Answers1

1

As your array does not actually contain the sequence "1,2,3" the i will increment to 3 and then your check for "i+3" will access element #6 which is out of bounds. Your loop should probably be for i in range(len(nums)-len(searchString)) with searchString = "123".

Please add the language as Tag to your questions.

lathspell
  • 3,040
  • 1
  • 30
  • 49
  • Thanks for the info, can you also help me in understanding how the logic is working here, if you done mind, with 1-2 examples. – gauravminhas Apr 28 '20 at 09:19
  • You walk from left to right through your array and at each position you check if the next three numbers are exactly 1,2,3. If so, you return immediately, if not you go one step further to the right. Try adding some print() statements to understand the algorithm. – lathspell Apr 28 '20 at 09:22