Python sum() function


The sum() function in Python returns the sum of all elements in an iterable (e.g., list, tuple) or the sum of two or more numbers, optionally starting with an initial value.

Syntax

sum(iterable, start=0)
  • iterable: The iterable (like a list, tuple, or set) containing the items to be summed.
  • start (optional): The value to start with. This is added to the sum of the items in the iterable. It defaults to 0.

Return Value

  • Returns the total sum of the elements in the iterable, starting from the start value if provided.

Examples

  1. Summing a list of numbers:

    numbers = [1, 2, 3, 4, 5] print(sum(numbers)) # Output: 15
  2. Using sum() with a start value: The start value is added to the sum of the iterable.

    numbers = [1, 2, 3] print(sum(numbers, 10)) # Output: 16 (10 + 1 + 2 + 3)
  3. Summing a tuple of numbers:

    numbers = (4, 5, 6) print(sum(numbers)) # Output: 15
  4. Summing using a start value of 0 (default): If no start value is provided, it defaults to 0.

    numbers = [7, 8, 9] print(sum(numbers)) # Output: 24 (7 + 8 + 9)
  5. Summing with a set: You can use a set with the sum() function as well.

    numbers = {1, 2, 3} print(sum(numbers)) # Output: 6
  6. Summing with a generator expression: You can pass a generator expression to sum().

    print(sum(i**2 for i in range(1, 4))) # Output: 14 (1 + 4 + 9)

Points to Remember

  • The sum() function works with numbers, and it cannot directly sum strings or non-numeric types.
  • It is more efficient for numeric types and sequences but is not suitable for concatenating strings. For string concatenation, use the join() function instead.

Summary

  • The sum() function is used to calculate the sum of numbers in an iterable.
  • An optional start value can be provided, which is added to the total sum.
  • Works with iterables like lists, tuples, sets, and generator expressions.