sum for sequences?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Mar 29 23:49:46 EDT 2010


On Mon, 29 Mar 2010 19:31:44 -0700, Patrick Maupin wrote:

> It's about a lack of surprises.  Which, 99% of the time, Python excels
> at.  This is why many of us program in Python.  This is why some of us
> who would never use sum() on lists, EVEN IF IT WERE FIXED TO NOT BE SO
> OBNOXIOUSLY SLOW, advocate that it, in fact, be fixed to not be so
> obnoxiously slow.

As I said, patches are welcome. Personally, I expect that it would be 
rejected, but that's not my decision to make, and who knows, perhaps I'm 
wrong and you'll have some of the Python-Dev people support your idea.

sum is not designed to work with lists. It happens to work because lists 
happen to use + for concatenation, and because it is too much trouble for 
too little benefit to explicitly exclude lists in the same way sum 
explicitly excludes strings. In the Python philosophy, simplicity of 
implementation is a virtue: the code that is not there contributes 
exactly no bugs and has precisely no overhead.

sum has existed as a Python built-in for many years -- by memory, since 
Python 2.2, which was nearly nine years ago. Unlike the serious gotcha of 
repeated string concatenation:


# DO NOT DO THIS
result = ""
for s in items:
    result += s


which *does* cause real problems in real code, I don't believe that there 
have been any significant problems caused by summing lists of lists. As 
problems go, it is such a minor one that it isn't worth this discussion, 
let alone fixing it. But if anyone disagrees, this is open source, go 
ahead and fix it. You don't need my permission.



-- 
Steven



More information about the Python-list mailing list