Python Forum
simulating sum function on LIST - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: simulating sum function on LIST (/thread-2195.html)



simulating sum function on LIST - vvv - Feb-25-2017

Hi All,

I am a newbie to python. Trying to simulate the sum function to add all the values in a LIST
#list 
orig= [1,2,3,4,5]

#function
def sum2(data):
    a=0
    for i in data:
        a=a+i
        return a 

#calling function
sum2(orig)
Output:
#result 1
i am expecting (15) .

I am trying this code in anacondo Spyder.

where am i going wrong????


RE: simulating sum function on LIST - Skaperen - Feb-25-2017

the return is inside the loop an so the return happens the first round of the loop.  whatever is in the first position of the list, that is what is returned.  to fix this, use less indenting of the return so that it is the same as the for line.


RE: simulating sum function on LIST - vvv - Feb-25-2017

Thanks Skaperen..It worked.. Big Grin
#final code
def sum2(data):
    a=0
    for i in data:
        a=a+i
    return a