sum() Function in Python

Python sum() Function

In Python, the sum() function is a built-in function that allows you to calculate the sum of elements in an iterable, such as a list, tuple, set, or any other iterable object. It takes the iterable as its argument and returns the sum of all the elements in that iterable.

Here's the basic syntax of the sum() function:

sum(iterable, start=0)

Parameters:

  • iterable: The iterable (list, tuple, set, etc.) whose elements you want to sum.
  • start (optional): The initial value of the sum. If not provided, it defaults to 0.

Sum of a List:

numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)  # Output: 15

Sum of a Tuple:

numbers = (5, 10, 15)
total = sum(numbers)
print(total)  # Output: 30

Sum of a Set:

numbers = {2, 4, 6, 8}
total = sum(numbers)
print(total)  # Output: 20

Sum with a Start Value:

numbers = [1, 2, 3, 4, 5]
start_value = 10
total = sum(numbers, start_value)
print(total)  # Output: 25 (10 + 1 + 2 + 3 + 4 + 5)

Remember that the sum() function works only with numerical data types (e.g., integers, floats). If you try to use it with non-numeric data types, you will encounter a TypeError. Also, be cautious when using the start parameter, as it changes the initial value of the sum.