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

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 1:[1]

You can add all things by converting them into a string:

things = [1, 3.14, "string", object()]
result = ""
for thing in things:
    result += str(thing)
print(result)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Thomas Weller