samedi 3 août 2019

What's the best way to write an if statement that won't break on an out of bounds check?

In a for loop, what's the best way to check a previous and next in a list without getting an index out of bounds? (See code below)

Let's say I'm writing a function to check if every color is next to another of the same color, such as:

def colorChecker(colorList):
    colors = True
    for i in range(len(colorList)):
        if not ((i > 0 and colorList[i] == colorList[i-1]) or (i < len(colorList) and colorList[i] == colorList[i+1])):
            colors = False
    return colors

This gives me an index out of bounds exception...

I'm attempting to check for the index out of bounds and bounce it from the if statement before it goes into checking colorList[len(colorlist)+1]...but obviously this isn't the correct way to do it. How would you better write this?

Aucun commentaire:

Enregistrer un commentaire