sum () function in Python3 has a signature
SUM (ITERABLE, START = 0) . What is the reason that
Start is initially initialized by zero?
Why not initialize
start inside the function itself the first object of the collection, if present, and otherwise return
Why can it be useful? To begin with, just that the operation of the function corresponds to expectations: if the
__ Add method is implemented for me, I want to fold it, and I expect the function of the amount to me all my objects in one, and will not crash With the error
Answer 1, Authority 100%
The correct type of return value, as already mentioned in the Xander’s comments – this is, in my opinion, the main reason for such behavior
Sum . Take a simple example:
def my_super_sum (arr1, arr2): RETURN SUM (ARR) * 2 - SUM (ARR2)
In the event that
Sum knows exactly what works with numbers, there will be no problems here at any complimentary collection
ARR2 . Whatever numbers (in the form of an iterator) nor submit this function to the input, including empty collections (yes, it happens, and it is completely normal) – everything will work if the
Sum function from an empty collection returns
0 . But not if it returns
None . Well, either then you have to change the behavior of python when adding numbers with
None , considering it zero. In short, all the current behavior of python “saves”.
Problem with your option is that
python is a language without strict typing, so empty, for example, the list has no type. No items – no type. No type – it is not clear that we summarize and how.
And there may also be a collection of mixed types. In the Pythonovsky list there may be arbitrary elements, any types, inversion. Therefore, to focus on the first element in this case somehow very not on Pitonovski.
How correctly removed MrevGenx if you want to navigate the first element of the sequence – do it explicitly using the
Reduce function, which is precisely for this option and sharpened.