Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Looping back to why sum doesn't work with strings, it looks like they implemented it like this:

    >>> def sum(it):
    ...   return reduce(operator.add, it, 0)
Basically the first value is always added to 0. This has one important difference which can be a valid compromise if you expect to almost always sum numbers. If you try to call add([]) without the initial 0, you'll get an error because there's no way to know what the zero value is.

In a typed language you could use type inference and use the inferred type's zero value (if the language has such a concept for all types like for example Go does). In Python I guess you could fall back to None, but then you'd have code that doesn't behave consistently for all inputs.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: