@Gypsy Morrison has already given you the solution to this problem. But, if you allow me I will give you suggestions for correction:
Why the i = 0
at the beginning? It is not necessary, the value of i
in the first round of the cycle is already going to be 0 because its xrange(0,len(lista)): ...
starts at 0.
No need to increase 1 to i
at the end of the loop, the construction of the cycle for
is already doing it automatically
I mean, I’d be:
lista = [1,2,3,4]
soma = lista[0]
for i in xrange(0, len(lista) - 1):
if lista[i] != lista[i + 1]:
soma += lista[i + 1]
print soma # 10
Note that with this code you will only add to soma
if two values in the list are not equal or consecutive because of the if lista[i] != lista[i + 1]: ...
.
That is if the list was [1,2,2,2]
the result would be 3, because the second and the last 2 (lista[2]
, lista[3]
), which have equal values to the above, would not be counted.
PS: Beware of the title of the question "Adding consecutive integers", because what you are doing with this code (if this is really the logic you presented) is more "Adding integers that are not equal or consecutive"