1

Suppose I have a list of characters that I want to make a string out of. I can add them like this:

In [1]: s = [x for x in "hello"]

In [2]: s[0] + s[1] + s[2] + s[3] + s[4]    # Works
Out[2]: 'hello'

But adding via sum() doesn't work. This surprised me, because in my mental model, sum() should just reduce each element in the list via +.

In [3]: sum(s)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-a1d2094b79e8> in <module>
----> 1 sum(s)

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

Nor can I call str() on a list of characters:

In [4]: str(s)
Out[4]: "['h', 'e', 'l', 'l', 'o']"

For comparison, in Julia I can do

julia> s = [x for x in "hello"]
5-element Array{Char,1}:
 'h': ASCII/Unicode U+0068 (category Ll: Letter, lowercase)
 'e': ASCII/Unicode U+0065 (category Ll: Letter, lowercase)
 'l': ASCII/Unicode U+006C (category Ll: Letter, lowercase)
 'l': ASCII/Unicode U+006C (category Ll: Letter, lowercase)
 'o': ASCII/Unicode U+006F (category Ll: Letter, lowercase)

julia> prod(s)
"hello"

julia> String(s)
"hello"

(Note that string concatenation is done by taking products instead of sums in Julia.)

I include the comparison because if anything, I would expect this to work in Python and fail in Julia, since Julia actually distinguishes between string and character data types. The Julia variable s is an array of Chars while the Python variable s is a list of strs.

I assume the reason this works in Julia is "because someone enabled it to," so my question is instead about Python:

  • Why does the sum() call fail to concatenate strings in Python?
  • Why does the error message claim that Python is trying to add an int to a str? Where is the int?

Please note that I am not asking about how to concatenate a list of strings (which can be done using "".join()).

Max
  • 695
  • 5
  • 18
  • 4
    `sum()` has an implicit start value of `0`. It also actively refuses to work on strings if you change the start value because concentrating strings this way is inefficient. – Klaus D. Mar 17 '21 at 08:22
  • You could set initial value with sum(s, ''), but it is actively refused in favor of join. See https://stackoverflow.com/questions/3525359/python-sum-why-not-strings – Lesiak Mar 17 '21 at 08:24

0 Answers0