find the sum of a list of numbers in python

To find the sum of a list of numbers in python, you can use the built-in function called sum(). Simply pass in your list of numbers as an argument to the function like so:

main.py
my_list = [1, 2, 3, 4, 5]
sum_of_list = sum(my_list)
print(sum_of_list)
72 chars
4 lines

This will output the sum of the list (which in this case is 15).

If you're working with a very large list, you can also use the math.fsum() function, which is more accurate for floating-point numbers:

main.py
import math

my_list = [1.5, 2.7, 3.9, 4.2, 5.1]
sum_of_list = math.fsum(my_list)
print(sum_of_list)
101 chars
6 lines

This will output the sum of the list (which in this case is 17.4).

related categories

gistlibby LogSnag