Python: Sum all the items in a list
Sum Items in List
Write a Python program to sum all the items in a list.
Visual Presentation:
Sample Solution:
Python Code:
# Define a function called sum_list that takes a list 'items' as input
def sum_list(items):
# Initialize a variable 'sum_numbers' to store the sum of the numbers
sum_numbers = 0
# Iterate through each element 'x' in the input list 'items'
for x in items:
# Add the current element 'x' to the 'sum_numbers' variable
sum_numbers += x
# Return the final sum of the numbers
return sum_numbers
# Call the sum_list function with the list [1, 2, -8] as input and print the result
print(sum_list([1, 2, -8]))
Sample Output:
-5
Explanation:
In the above exercise -
def sum_list(items): -> This line defines a function called “sum_list” that takes a single argument items. This function will be used to calculate the sum of all the numbers in the items list.
- sum_numbers = 0 -> This line initializes a variable called sum_numbers to zero. This variable will be used to keep track of the running total of the sum of the numbers in the list.
- for x in items: -> This line starts a loop that will iterate over each element in the items list, one at a time.
- sum_numbers += x -> This line adds the current value of x to the sum_numbers variable. This is equivalent to the shorter form sum_numbers = sum_numbers + x.
- return sum_numbers -> This line returns the final value of the sum_numbers variable after the loop has finished.
print(sum_list([1,2,-8])) -> This line calls the sum_list function and passes in the list [1,2,-8]. The resulting sum is then printed to the console using the print() function.
Flowchart:
Python Code Editor:
Previous: Python List Exercise Home.
Next: Write a Python program to multiply all the items in a list.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics