Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sum() function with list parameter

I am required to use the sum() function in order to sum the values in a list. Please note that this is DISTINCT from using a for loop to add the numbers manually. I thought it would be something simple like the following, but I receive TypeError: 'int' object is not callable.

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

I looked at a few other solutions that involved setting the start parameter, defining a map, or including for syntax within sum(), but I haven't had any luck with these variations, and can't figure out what's going on. Could someone provide me with the simplest possible example of sum() that will sum a list, and provide an explanation for why it is done the way it is?

like image 858
Ro Mc Avatar asked Sep 10 '13 23:09

Ro Mc


People also ask

How do you sum a function in a list Python?

Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers. start : this start is added to the sum of numbers in the iterable.

Can you sum lists in Python?

Python's built-in function sum() is an efficient and Pythonic way to sum a list of numeric values. Adding several numbers together is a common intermediate step in many computations, so sum() is a pretty handy tool for a Python programmer.

What is sum () in Python?

Python sum() Function The sum() function returns a number, the sum of all items in an iterable.


1 Answers

Have you used the variable sum anywhere else? That would explain it.

>>> sum = 1
>>> numbers = [1, 2, 3]
>>> numsum = (sum(numbers))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

The name sum doesn't point to the function anymore now, it points to an integer.

Solution: Don't call your variable sum, call it total or something similar.

like image 144
flornquake Avatar answered Sep 23 '22 12:09

flornquake