restriction on sum: intentional bug?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sat Oct 17 03:25:25 EDT 2009
On Fri, 16 Oct 2009 18:01:41 -0700, Jon Clements wrote:
> Sum should return a *numeric* result, it has no way to do anything
> sensible
> with strings -- that's up to the coder and I think it'd be an error in
> Python
> to not raise an error.
That's obviously wrong in Python.
Mathematically, sum() is defined as the repeated application of the +
operator. In Python, the + operator is well-defined for strings and lists
as well as numbers. Since you can say "ab" + "cd" + "ef" and get a
sensible result, then sum() should be able to do the same thing.
And indeed, if you pass a list-of-lists to sum(), it does:
>>> sum([[1,2], ['a',None], [1,'b']], [])
[1, 2, 'a', None, 1, 'b']
(For the record, summing lists is O(N**2), and unlike strings, there's no
optimization in CPython to avoid the slow behaviour.)
Likewise if you defeat sum()'s feeble attempt to stop you from running
with scissors, it also gives a sensible result for strings:
>>> class S:
... def __add__(self, other):
... return other
...
>>> sum(['a', 'b', 'c', 'd'], S())
'abcd'
In languages where + is *not* used for string or list concatenation, then
it makes sense to argue that sum(strings or lists) is meaningless. But
Python is not one of those languages.
--
Steven
More information about the Python-list
mailing list