Python Forum
simulating sum function on LIST
Thread Rating:
  • 3 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
simulating sum function on LIST
#1
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????
Reply
#2
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#3
Thanks Skaperen..It worked.. Big Grin
#final code
def sum2(data):
    a=0
    for i in data:
        a=a+i
    return a
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I created a function that generate a list but the list is empty in a new .py file mrhopeedu 2 2,248 Oct-12-2019, 08:02 PM
Last Post: mrhopeedu
  Simulating events using Hawkes akshit2291 1 2,115 Sep-25-2018, 04:17 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020