How to sum in python

Mondo Technology Updated on 2024-01-30

In Python, summing is a common arithmetic. For a series of numbers, we usually use the built-in sum() function to sum them. Here are some examples:

python

List of numbers.

numbers = [1, 2, 3, 4, 5]

Use the sum function.

total = sum(numbers)

print(total) output: 15

The sum() function can take a list, tuple, or collection and return the sum of its elements.

If you have a string that contains a series of numbers, you can use the split() function to split it into a list and then use the sum() function to sum it. For example:

python

A string that contains a number.

s = "1 2 3 4 5"

Use the split() function to split the string, and then use the sum() function to sum it.

total = sum(map(int, s.split())

print(total) output: 15

In this example, we first use the split() function to split the string into a list ["1", "2", "3", "4", "5"]`。We then use the map() function to convert each element in the list to an integer, resulting in a new list [1, 2, 3, 4, 5]. Finally, we use the sum() function to sum.

If you want to ask for a very large number, you may need to use mathfsum() function, which is more precise:

python

import math

A list of large numbers.

numbers = [1000000000, 2000000000, 3000000000]

Use mathfsum function.

total = math.fsum(numbers)

print(total) output: 600000000000

In this example, we use mathfsum() function. This function is more precise than sum(), especially when dealing with large numbers.

Related Pages