Yandex

Python sum() Function – Add Items of an Iterable



Python sum() Function

The sum() function in Python returns the total (sum) of all items in an iterable, such as a list or tuple. It’s one of the most frequently used functions in real-world Python programs.

Syntax

sum(iterable, start=0)

Parameters:

  • iterable – A sequence like a list, tuple, or set containing numeric values.
  • start – (Optional) The value to start with. Default is 0.

Returns:

  • The sum of all items in the iterable plus the start value.

Example 1: Sum of a List

numbers = [10, 20, 30]
print(sum(numbers))
60

Example 2: Sum with Start Value

numbers = [1, 2, 3]
print(sum(numbers, 10))
16

Why? Because 1 + 2 + 3 = 6 and 6 + 10 = 16

Example 3: Sum of a Tuple

values = (5, 15, 25)
print(sum(values))
45

Use Case: Total Bill Calculation

items = [120.5, 250.0, 89.99]
total = sum(items)
print("Total Bill:", total)
Total Bill: 460.49

Common Mistakes

  • Using sum() with non-numeric values like strings or dictionaries will raise a TypeError.
  • Don’t use it for concatenating strings — use ''.join() instead.

Interview Tip

sum() is commonly used in problems that ask for totals, averages, or when working with filter() and map().

Summary

  • sum() adds all elements in an iterable.
  • You can use an optional start value.
  • Only use it with numbers; using it with strings or mixed types causes errors.

Practice Problem

Write a program that asks the user for 5 numbers and prints their sum.

numbers = []
for i in range(5):
    num = float(input("Enter number " + str(i+1) + ": "))
    numbers.append(num)

print("Sum =", sum(numbers))


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M