The problem is that if lista[i] == lista[i+1]
compares whether the element is equal to the next. And since the list has no repeated elements, the result will always be empty (as it will never enter this if
).
A solution would be to scroll through the list from the second element and check if it is equal to "previous + 1":
lista = [1, 2, 3, 5, 9, 10]
result = []
in_seq = False
for i in range(1, len(lista)):
if lista[i] == lista[i - 1] + 1:
if not in_seq:
result.append(lista[i - 1])
in_seq = True
result.append(lista[i])
else:
in_seq = False
print(result)
I also used the variable in_seq
to know if I’m in the middle of a sequence, because if I’m not, I also have to include the previous element in the result.
The result is:
[1, 2, 3, 9, 10]
Perfect, I could understand everything that was explained.
– bruno boff