Home python Why Sum () in Python assumes that there are exactly numbers in...

Why Sum () in Python assumes that there are exactly numbers in the collection?

Author

Date

Category

The 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 none ?

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 Typeerror .


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 ARR1 and 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.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions