mardi 14 avril 2020

(Python) Function to check if a element is the same as the next, returns IndexError when examining the last element

I'm trying to make a block of code in Python, to check if an element in a number is the same as the next element. The problem is that, when the if statement checks the last element, it can't check if it's the same as the next, since there is no next element.

My code:

 for i, elem in enumerate(number):
    if elem == number[i + 1]:
        count = count + 1
    else:
        break

new_num = count + elem + index

This returns

if elem == number[i + 1]:
IndexError: index out of range

Is it better to use a while loop, or can it be fixed with try and except statements? I tried both, but not sure if i used it right.

Aucun commentaire:

Enregistrer un commentaire