Search code examples
pythonlistfunctionsumpythomnic3k

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.


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