深度阅读

How to sum the elements in a list in Python using a `for` loop

作者
作者
2023年08月22日
更新时间
10.85 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。