Hacker News new | past | comments | ask | show | jobs | submit login

Python's implementation of sum doesn't care about types, the function looks something like:

    def sum(iterable):
        r = 0
        for v in iterable:
            r += v
        return v

it always starts with an integer, and since int.__add__(str) returns NotImplemented it tries str.__radd__(int) instead, which raises an AttributeError because str has no method __radd__, so no summing of strings and integers.



Actually Python does explicitly reject strings.

  >>> sum(['hello', ' world'], '')
  TypeError: sum() can't sum strings [use ''.join(seq) instead]
But this is done explicitly against strings. They would _just work_ if not for this restriction, because based on usage they should work.




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: