saran
saran

Reputation: 368

Print the sum of the list using functions in Python

sum=0
def sum_list(list):
    for x in list:
        sum=sum+x
        return sum
list=[1,2,3,4,5]
print(sum_list) 

The output of the code is : <function sum_list at 0x10d06a1e0>

Why is it pointing to the memory address not the sum of the list?

Upvotes: 0

Views: 2700

Answers (2)

zenwraight
zenwraight

Reputation: 2000

You need to pass the list array like this:-

def sum_list(lst):
  sum = 0
  for x in lst:
    sum=sum+x
  return sum

lst=[1,2,3,4,5]
print(sum_list(lst)) 

Upvotes: 2

PacketLoss
PacketLoss

Reputation: 5746

You should just use sum(). If you cannot and want to sum using a function, please change your variable names!

When you call the inbuilt function sum it returns

sum
<built-in function sum>

myList = [1, 2, 3, 4, 1155]
sum(myList)
#1165

Now if you do what you have done, and set sum to 0 it returns

sum
0

This renders you unable to use the function sum

sum = 0
mylist = [1, 2, 3, 4, 5]
sum(mylist)
Traceback (most recent call last):
  File "<pyshell#44>", line 1, in <module>
    sum(mylist)
TypeError: 'int' object is not callable

Upvotes: 1

Related Questions