Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sum() function to sum all items in a given list

there is a function I want to define that takes all items in a list and adds them up together:

def sum():

for x in range(len(user)):
    sum = 0
    sum =+ user[x]
    return sum

user = [1,1,1]
score = sum()
print(score)

for some reason it prints just 1, and my wanted output is 3.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Given a list of integers you could do this:

my_list = [1, 1, 1]

def accumulation(list_):
  total = 0
  for i in list_:
    total += i
  return total

…or…

sum(my_list) # where sum is the Python built-in function
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading