Write a Python program to sum all the items in a list

Sum all the items in a list

This program defines a function sum_list_items that takes a list (lists) as input and returns the sum of all its items. Then, it demonstrates the usage of this function with an example list [5, 5, 5, 8]. Below this page there is an python code editor try it by yourself

# define a function sums that take lists as a parameter
def sum_list_item(lists):
    # initalize a variavle name total_sum that store sum of number
    total_sum = 0
    # iterating every item of list through item
    for item in lists:
        # adding old sum of the number into total_sum and initalize variable with same 
        total_sum += item
        # return the sum of list's number
    return total_sum


print(sum_list_item([5, 5, 5, 8]))

Output:

23

Explanation:

In Above excercise:

def sum_list_item(lists): this line of code defines the function named sum_list_item that takes lists as a parameter.

  • total_sum = 0 this is an variable that store the sum of numbers
  • for item in lists: this is an for loop that iterate over each item of the list
  • total_sum += item this line of code sum the item in previous one and initialize the variable with same name. This is an equals to total_sum = total_sum + item
  • return total_sum this lines of code return the sum of all items


Follow on:
Sunil Shaw

Sunil Shaw

About Author

I am a Web Developer, Love to write code and explain in brief. I Worked on several projects and completed in no time.

Related Page