The sum() function in Python is used to sum the numbers in a list. Summing a list of numeric values is a useful and mandatory thing everywhere. So for a Python programmer, sum() is a useful tool. You can match lists and tuples together by using sum().
Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related Python fuction queries.
In this context, we shall look into how to use the sum() function of Python.
The sum() function prints out the sum of the values of the list. Basically, the sum() function can be used to calculate the sum of all values in an iterable object. This method is useful when you need the total value of a list of items, which is common in a number of mathematical calculations.
The Python sum() function adds up all the numerical values in an iterable, such as a list, and returns the total of those values. sum() calculates the total of both floating-point numbers and integers.
For instance, you could use the sum() method to calculate the total price of the products a customer purchases at a store.
Here's the syntax for the Python sum() method:
$ sum(iterable_object, start_value)
The function sum() takes in two parameters:
sum() returns the sum of start and items of the given iterable.
1. Take a look at the below function:
a = (1, 2, 3)
x = sum(a)
print(x)
It's output will give:
6
2. The basic sum() function:
a = (3, 4, 5)
# Apply sum() function
x = sum(a)
# Return result
print("Sum =",x)
It's Output will give:
Sum = 12
3. Increase results:
a = (3, 4, 5)
# Apply sum() function
x = sum(a)
print(x)
# Plus 10
y = sum(a, 10)
print(y)
Output will give:
12
22
This article covers how to use the sum() function in Python. In fact, the sum() function adds the items of an iterable and returns the sum. Also it calculates the total of all numerical values in an iterable. sum() works with both integers and floating-point numbers. The sum() function has an optional parameter to add a number to the total.