5 ms·
Python's implementation of sum doesn't care about types, the function looks something like: def sum(iterable): r = 0 for v in iterable:
by voidiac 10y ago
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.
- clusmore 10y agoActually 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.