Saturday, October 24, 2009

Python - Adding numbers in a list


Lets see some of ways in python to add the numbers present in a list.

Suppose:

>>> numlist = [10,20,5,30]
>>> numlist
[10, 20, 5, 30]
>>> print sum(numlist)
65

Using python built in function 'reduce'

>>> numlist
[10, 20, 5, 30]
>>> def add(x, y): return x + y
...
>>> sum = reduce(add, numlist)
>>> sum
65

Enhancing the above using python 'lambda' function

>>> numlist
[10, 20, 5, 30]
>>> reduce(lambda b,a: a+b, numlist)
65
>>>

Or using python for loop:

>>> numlist
[10, 20, 5, 30]
>>> sum = 0
>>> for i in numlist:
... sum += i
...
>>> sum
65
>>>

1 Comment:

maalu said...

when I try to run the programs,showing the error message
File "sum.py", line 1
>>> numlist = [10,20,5,30]
^
SyntaxError: invalid syntax
File "su1.py", line 1
>>> numlist = [10,20,5,30]
^
SyntaxError: invalid syntax
How to solve this error?