Python Forum

Full Version: simulating sum function on LIST
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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????
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.
Thanks Skaperen..It worked.. Big Grin
#final code
def sum2(data):
    a=0
    for i in data:
        a=a+i
    return a