Home > Mobile >  sum() function to sum all items in a given list
sum() function to sum all items in a given list

Time:07-03

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.

CodePudding user response:

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

CodePudding user response:

You re-define sum for each x which means that your sum is always user[x]. Additionally, you return immediately after the first x element.

A possible solution is this:

def sum(user):
    sum = 0
    for u in user:
        sum  = u
    return sum

print(sum([1,1,1]))

CodePudding user response:

I think you have forgotten to ident your for loop:

def sum():

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

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

should be...

def sum():

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

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

...to achieve your expected result.

  • Related