0

Is there a way to overload the built-in function sum() so that it works on a user defined iterable? Assume the elements in the iterable can be added using +. For instance strings.

Specifically I want to be able to do the following

S = StrListIterable([<list of strings>])
concatedList = sum(S) # returns a concatenated string of all strings in S

I can obviously achieve this using a simple join statement on elements of S but I was wondering if Python offers support to overload some of the standard built-ins.

user2399453
  • 2,930
  • 5
  • 33
  • 60
  • You should be able to check which method `sum` uses and have a class which implements it – Simon Fraser Jul 23 '17 at 18:48
  • 4
    You can already use it on iterables of things besides integers. It just has a specific block to prevent you from using it on strings. – BrenBarn Jul 23 '17 at 18:52
  • `sum` can certainly work with non-numeric types, you just have to give it a suitable starting value. However, as [the `sum` docs](https://docs.python.org/3/library/functions.html#sum) and several people here have mentioned it will complain if you try to use it to join strings. But you can do, eg, `sum(list_of_lists, [])` to concatenate a bunch of lists. – PM 2Ring Jul 23 '17 at 18:59
  • 3
    The reason that `sum` won't concatenate strings is that it would be inefficient compared to using `.join`. Similar remarks apply to string concatenation via `reduce`, although using `reduce` (or `+=` in a `for` loop) isn't as bad as it was before Python 2.5 because `str` has had some optimizations to handle this type of concatenation because so many people were using `+` concatenation instead of `.join`. Some people are _not_ happy about this, eg Python core dev [Alex Martelli](https://stackoverflow.com/a/1350289/4014959). – PM 2Ring Jul 23 '17 at 19:21

2 Answers2

0

You don't use sum to concatenate strings in python. You use join:

>>> S = StrListIterable([<list of strings>])
>>> concatedList = ''.join(S) # returns a concatenated string of all strings in S

Where '' (empty string) is the joiner.

TimeHorse
  • 510
  • 3
  • 14
-1

The start argument provides an initial value to add to. But:

>>> L = ['foo', 'bar', 'baz']
>>> sum(L, '')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]
>>> ''.join(L)
'foobarbaz'
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358