Adding consecutive integers to a list - Python

Asked

Viewed 1,278 times

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’re making the following mistake: IndexError: list index out of range.

How do I solve this problem?

2 answers

2


@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"

0

'Cause you’re reading a position that doesn’t exist when i == 3 (last iteration). The correct one 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.