Reputation: 5946
Is there a smart way to sum a list, but actually perform a map type function prior to summing.
I'm trying to combine these functions into one function that uses the lambda:
xlist = [1, 2, 3, 4]
sum(map(lambda x: (x - 1.0)**2, xlist))
# result = 14.0
I'm trying this:
reduce(lambda x, y: x + (y - 1.0)**2, xlist)
# result = 15.0
But it is not the same result. What is the smartest way to solve this. I'm kind of curious, I know I can use sum(map())
but I wonder if reduce can be used in this way.
Upvotes: 1
Views: 417
Reputation:
Yea, you just need to pass an initial value of 0
:
>>> xlist = [1, 2, 3, 4]
>>> reduce(lambda x, y: x + (y - 1.0)**2, xlist, 0)
14.0
>>>
Keep in mind though that reduce
is generally hated by Python programmers because of how unreadable it is. You would probably be better off using the first approach.
Or, even better, use a generator expression:
sum((x - 1.0)**2 for x in xlist)
This is a lot easier to read and is also more efficient because map
creates an unnecessary list.
Upvotes: 7