How to sum the elements in a list in Python using a `for` loop
Published on Aug. 22, 2023, 12:16 p.m.
To sum the elements in a list in Python using a for loop, you can iterate through the list and add each element to a sum variable. Here is an example:
my_list = [1, 2, 3, 4, 5]
sum = 0
for num in my_list:
sum += num
print("The sum of the list elements is:", sum)
In this example, we first initialize a list called my_list with some numbers. We then initialize a variable called sum to 0 outside of the loop. We use a for loop to iterate through each element in my_list, and use the += operator to add each element to the sum variable. Finally, we use the print() function to output the total sum to the console.
The output of this program will be:
The sum of the list elements is: 15
Note that you can also use the built-in sum() function in Python to sum the elements in a list:
my_list = [1, 2, 3, 4, 5]
sum = sum(my_list)
print("The sum of the list elements is:", sum)
This code will output the same result as the previous example. The sum() function takes a sequence, like a list, and returns the sum of its elements.