Python has a built in function sum
, which is effectively equivalent to:
def sum2(iterable, start=0):
return start + reduce(operator.add, iterable)
for all types of parameters except strings. It works for numbers and lists, for example:
sum([1,2,3], 0) = sum2([1,2,3],0) = 6 #Note: 0 is the default value for start, but I include it for clarity
sum({888:1}, 0) = sum2({888:1},0) = 888
Why were strings specially left out?
sum( ['foo','bar'], '') # TypeError: sum() can't sum strings [use ''.join(seq) instead]
sum2(['foo','bar'], '') = 'foobar'
I seem to remember discussions in the Python list for the reason, so an explanation or a link to a thread explaining it would be fine.
Edit: I am aware that the standard way is to do "".join
. My question is why the option of using sum for strings was banned, and no banning was there for, say, lists.
Edit 2: Although I believe this is not needed given all the good answers I got, the question is: Why does sum work on an iterable containing numbers or an iterable containing lists but not an iterable containing strings?
+
as the concatenation operator. Still doesn't make sense to sum strings. – Fullmer+
to concatenate them. You can sum two strings using+
to concatenate them. So it makes as much sense to define sum as concatenation for strings as it is for lists. That is what I meant. Whether this is good or is bad is beside the question. – Mcgawsum
and"".join
? – Mcgawsum("abc")
andsum([1,2,3])
is what I understood you to be asking about. You can claim it's clear all you want, but it actually confused me and I actually asked. – Madelenemadelinsum
know about the string special case. Anyway, I have explained in that comment you replied to, and I have edited the question. Thanks for your input. – Mcgawsum("abc")
andsum([1,2,3])
and nothing more. You can claim that I should have done some mysterious due diligence to determine that your question wasn't trivially bad. I read a lot of bad SO questions. There is no magical due diligence for separating bad questions from good. I can only ask. You can revise your question to make it clear. When one person bothers to ask for clarification you have to take that as evidence that something's wrong with the question. – Madelenemadelin','.join('foo')
, for example, returns'f,o,o'
.) – Commutatesum2
should be more likereturn reduce(operator.add, iterable, start)
.reduce
can also take an optionalstart
parameter, and if omitted, unlikesum
, would raise an Exception when given an empty sequence. – Biegel