vendredi 9 août 2019

I get "list index out of range" for a boolean but not when I use that boolean in a for and if loop?

I have written a function which, when given a list of integers, returns True when the list argument contains a 3 next to a 3 somewhere. Here is my code:

def has_33(nums):
    for i,num in enumerate(nums):
        if nums[0]==3 and nums[1]==3:
            return True
        elif nums[i+1]==3 and (nums[i+2]==3 or nums[i]==3):
            return True
        else:
           return False 

This function either returns True or False even though I realised

nums[i+1]

could be out of range when the loop reaches the last index.

E.g if I have a list defined as nums=[1,3,4,5], the function returns False. However, when I separately run

nums[4]==1

I get "IndexError: list index out of range" which I understand why but I don't understand why, in the function,

nums[i+1] or (nums[i+2] or nums[i]==3)

doesn't throw the same error when it reaches the last index of the list?

Aucun commentaire:

Enregistrer un commentaire