# 在 Python 中获取列表的总和

## 在 Python 中用 `sum()` 函数对一个列表求和

``````myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
listSum = sum(myList)
print(f"Sum of list -> {listSum}")
``````

``````Sum of list -> 55
``````

`sum()` 函数接受两个参数。第一个参数是可迭代的数据结构，第二个参数是起始索引。可迭代的数据结构可以是数字，Python 字典和元组的列表。起始索引基本上是可迭代数据结构中求和过程应从其开始的位置。

``````myList = ["1", "3", "5", "7", "9"]
myNewList = [int(string) for string in myList]
sum1 = sum(myNewList)
sum2 = sum(number for number in myNewList)
print(f"Sum of list -> {sum1}")
print(f"Sum of list -> {sum2}")
``````

``````Sum of list -> 25
Sum of list -> 25
``````

## 通过遍历列表获取列表的总和

``````myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
listSum = 0

for number in myList:
listSum += number

print(f"Sum of list -> {listSum}")
``````

``````Sum of list -> 55
``````

``````myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
length = len(myList)
listSum = 0

for i in range(length):
listSum += myList[i]

print(f"Sum of list -> {listSum}")
``````

``````Sum of list -> 55
``````

## 相关文章 - Python List

• 从 Python 列表中删除某元素的所有出现
• 在 Python 中将字典转换为列表
• 在 Python 中从列表中删除重复项
• 如何在 Python 中获取一个列表的平均值