[SOLVED] The sum function isn't universal. So which is?

Issue

I’ve recently used the sum() function on a list of characters. An error occurred:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

I’ve started writing a function for replacement and realised that the problem is that I’ve initialized a variable for the output to 0 and used a for loop for adding every element. That is probably done in the built-in function. I’ve realised that a solution is to initialize the before mentioned output variable to type(arr[0])(). I want to ask whether is there another built-in function for adding all elements of a list that is meant for all datatypes that support the addition operator.

Thanks for reaching out!

NOTE:
In the help(sum) it is clearly pointed out that the function is specifically for numerical values.

Solution

I believe functools.reduce() is what you’re looking for.

import functools
import operator

functools.reduce(operator.add, ["a", "b"])  # -> "ab"
functools.reduce(operator.add, [1, 2])      # -> 3

PS: if you look at the Python manual entry for reduce, they show what the implementation is "roughly equivalent to". Notice how the initial value is the first item itself by default, thus removing the problem of determining its type altogether. The consequence, however, is that if you call it with an empty list, you have to provide initializer or get a TypeError.

Answered By – joanis

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.