Here is my code, I need to sum an undefined number of elements in the list. How to do this?
l = raw_input()
l = l.split(' ')
l.pop(0)
My input: 3 5 4 9
After input I delete first element via l.pop(0)
.
After .split(' ')
my list is ['5', '4', '9']
and I need to sum all elements in this list.
In this case the sum is 18. Please notice that number of elements is not defined.
You can also use reduce method:
Furthermore, you can modify the lambda function to do other operations on your list.
Python iterable can be summed like so -
[sum(range(10)[1:])]
. This sums all elements from the list except the first element.You can use
sum
to sum the elements of a list, however if your list is coming fromraw_input
, you probably want to convert the items toint
orfloat
first:You can use
map
function and pythons inbuiltsum()
function. It simplifies the solution. And reduces the complexity.a=map(int,raw_input().split())
sum(a)
Done!
You can sum numbers in a list simply with the sum() built-in:
It will sum as many number items as you have. Example:
For your specific case:
For your data convert the numbers into
int
first and then sum the numbers:This will work for undefined number of elements in your list (as long as they are "numbers")
Thanks for @senderle's comment re conversion in case the data is in string format.