0

I was practicing a bit with a fairly new language for me, so I tried to write a simple function to add the elements of a list formed by integers, I then wrote a wrong program, and I realized that the variable on which it is iterated increases by two, ie:

lista = [1, 2, 3, 4]

def suma(lista):
    for i in lista:
        i += i
    return i

The final result is 8, then add two units in each iteration, although the program is wrong should not result in 4 and not 8? , I'm missing something but I do not know what it is. Thank you

EDIT:

If we write the following equivalent program:

def suma(lista):
    for i in lista:
        i += i
        print( i)
    return i

We obtain the following result:

2
4
6
8
8

?????? The last 8 corresponds to the return

1 Answer 1

1

You are adding i to itself, on the last iteration you are adding 4 + 4. You are not doing anything with the other iterations so you return the result of the last iteration i + i.

2
  • I think it's not like this
    – MARS
    Commented May 19, 2017 at 20:26
  • For every iteration of the loop you are adding each element of the array to itself. lista[0] += lista[0] which is 1 + 1 = 2, lista[1] += lista[1] which is 2 + 2 = 4, lista[2] += lista[2] which is 3 + 3 = 6, lista[3] += lista[3] which is 4 + 4 = 8 Commented May 19, 2017 at 20:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .