0

I know sum function works on an iterable of numbers for ex:

>>sum([1,2,3,4])
10
>>sum([[12,13],[2,3],[4,5],[])
[12,13,2,3,4,5]   This is a flatten output since the start value here is an empty list

Why doesn't sum function works for string if the start value is an empty string or any string?

>>sum(["abc","bcd"],"")    or sum(["abc","bcd"],"go")
TypeError: sum() can't sum strings [use ''.join(seq) instead]

However if I do the below it works

>>class ZeroString():
        def __add__(self,other):
            return other
>>print(sum(["go","there"],ZeroString()))
"gothere"

Could you please explain how does the above code works since __add__ method in ZeroString returns a string. This is similar to sum(["abc","bcd"],"") or sum(["abc","bcd"],"go") ?

sans0909
  • 395
  • 7
  • 20
  • 1
    This is a measure to avoid newcomers to use the highly inefficient string contraction massively. – Klaus D. Dec 26 '19 at 14:08
  • I imagine that the check was added specifically to prevent you using `sum` because it's an inefficient way to concatenate strings. Use `''. join(items)` instead. – khelwood Dec 26 '19 at 14:08
  • I just need to know how does the __add__ method of the above ZeroString class works here – sans0909 Dec 26 '19 at 14:10
  • 1
    It's not that it *doesn't* work, it's that Python explicitly prevents the use of `sum` when you pass it an iterable of strings and *only* an iterable of strings. If you don't match that exact usage pattern, e.g. in your case you pass `ZeroString()`, then Python doesn't explicitly prevent that since you may know what you're doing (‍♂️) and it just works like `str + str + str ...`. – deceze Dec 26 '19 at 14:14
  • The duplicate question answers your question. `ZeroString` isn't `string`, so the bit of code that rejects a `string` value in the `start` parameter doesn't reject a `ZeroString`. – John Coleman Dec 26 '19 at 14:14

0 Answers0