How to add up a list of items?

Question

As part of this exercise, the function has to add up the values for 4 parameters (food_bill, electricity_bill, internet_bill, rent) and compare against the budget parameter. If a list of expenses was provided instead of individual parameters, how could those be added easily?

Answer

The sum() function is provided by Python to easily add up a list of items. If given a list of numeric values, the sum() function will add them up and return the value of the summation.

expenses = (42, 17, 99, 34, 10)
print(sum(expenses))
# OUTPUTS: 202
10 Likes

but if I write like this:
def over_budget(budget,food_bill,electricity_bill,internet_bill,rent):
if budget<sum(food_bill,electricity_bill,internet_bill,rent):
return True

It gave me this: sum expected 2 arguments, got 4

Could you help explaining me why this error happened here?:grinning:

1 Like

The Python function sum() does not work like that.

1 Like

I appreciate your reply, could you explain it more? thank you so much

sum() is a built-in function to get the sum of an iterable (like a list), to add integers together just use + like you would do in math.

Look here, for instance: https://www.w3schools.com/python/ref_func_sum.asp

1 Like

As mentioned elsewhere, you have to use an iterable list, but that’s easy to do by enclosing the variable names in square brackets:

def over_budget(budget, food_bill, electricity_bill, internet_bill, rent):
  return sum([food_bill, electricity_bill, internet_bill, rent]) > budget
8 Likes
def over_budget(budget, food_bill, electricity_bill, internet_bill, rent):
  expenses = food_bill + electricity_bill + internet_bill + rent
  return budget < expenses
# Uncomment these function calls to test your over_budget function:
print(over_budget(100, 20, 30, 10, 40))
# should print False
print(over_budget(80, 20, 30, 10, 30))
1 Like

the most compact version:

def over_budget(a, *b):
  return a < sum(b)

first argument passed to function is assigned to a, any folowing arguments are assigned to list variable b. The sum() expects a list as argument so just passing over the obtained b list is enough.

read more about packing and unpacking variables
args and kwargs