I was wondering if map can be used at all to sum the elements of a list.
assume a = [1, 2, 3, 4]
list(map(sum, a))
will give an error that int object is not iterable
because list wants iterables.
map(sum, a)
is a valid statement but given the object, I do not see an easy way to dereference it.
[map(sum, a)]
will return an object inside the list
this answer states that it should be easy. What am I missing here?
To get the sum of all values in a Map :Initialize a sum variable and set it to 0 . Use the forEach() method to iterate over the Map . On each iteration, add the number to the sum , reassigning the variable.
In Python, you can use map() to apply built-in functions, lambda expressions ( lambda ), functions defined with def , etc., to all items of iterables such as lists and tuples.
map
applies a function to every element in the list. Instead, you can use reduce
:
a = [1, 2, 3, 4]
sum_a = reduce(lambda x, y:x+y, a)
In this case, purely sum
can be used, however, to be more functional, reduce
is a better option.
Or, in Python3:
from functools import reduce
a = [1, 2, 3, 4]
sum_a = reduce(lambda x, y:x+y, a)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With