Summing consecutive integers in a list - Python

2

I have the following code:

i = -0
soma = 0
lista = [1,2,3,4]
for i in xrage(0,len(lista)):
    if lista[i] != lista[i+1]:
        soma += lista[i]
    i+=1
print soma

You are giving the following error: IndexError: list index out of range.

How do I resolve this problem?

    
asked by anonymous 27.05.2016 / 05:45

2 answers

2

@Cigano Morrison has already given you the solution to this problem. But, if you will allow me to give you correction suggestions:

Why does i = 0 start? It is not necessary, the value of i in the first loop of the loop is already going to be 0 because its xrange(0,len(lista)): ... starts at 0.

Failure to increment 1 to i at the end of the loop, construction of for cycle is already doing this automatically

That is, it would look like:

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 soma if two list values are not equal or consecutive, because of the if lista[i] != lista[i + 1]: ... condition.

In other words, if the list was [1,2,2,2] , the result would be 3, since the second and last 2 ( lista[2] , lista[3] ), which have values equal to the previous elements, would not be counted. >

PS: Beware of the title of the question "Summing consecutive integers", because what you are doing with this code (if it is the same logic that presented) is more "Summing integers that are not equal or consecutive"

    
27.05.2016 / 11:28
0

Because you are reading a position that does not exist when i == 3 (last iteration). The correct would be:

i = 0
soma = 0
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]
    i += 1

print soma
    
27.05.2016 / 05:53