Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using map to sum the elements of list

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?

like image 803
Adorn Avatar asked Dec 21 '17 14:12

Adorn


People also ask

How do you use map sum?

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.

Can I use map on a list in Python?

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.


1 Answers

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)
like image 60
Ajax1234 Avatar answered Oct 01 '22 08:10

Ajax1234