0

I was doing a kind of simple Python exercise, the idea was to create a function that adds the numbers of a list. The problem is that when I run it the for loop skips several integers and I don't know why.

def simplearraysum(ar):
    sum = 0
    for number in ar:
        sum = sum + number
        ar.remove(number)
    return sum


list = [1, 2, 3, 4, 10, 11]

print(simplearraysum(list))

The output is 14, but it should be 31.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
SaturnDev
  • 161
  • 7
  • 1
    Why is the code modifying *the same list* being iterated? (Yes, that’s the answer. Perhaps a *copy* of the list could be created and iterated, or perhaps a *new* list could be created for the result.) – user2864740 Feb 16 '20 at 05:10
  • 1
    An easier way to do this is just type the list, and in the next line type ```print(sum(list))``` – TheRealTengri Feb 16 '20 at 05:15

1 Answers1

1

You should not modifying the list when it is being iterated. The for loop will take care of the elements in the list. Just comment the line and you will get the correct output:

def simplearraysum(ar):
    sum = 0
    for number in ar:
        sum = sum + number
        #ar.remove(number)
    return sum


list = [1, 2, 3, 4, 10, 11]

print(simplearraysum(list))

Saurabh Jain
  • 1,600
  • 1
  • 20
  • 30