Salih
Salih

Reputation: 381

Supplying another function to sum() as a start parameter

I have seen the below function in a tutorial about packaging.

My doubt is in sum() which takes Counter() as the start parameter. What would happen in this case?

# Import needed functionality
from collections import Counter

def sum_counters(counters):
  # Sum the inputted counters
  return sum(counters, Counter())

I tried replicating using the below code

a=[2,3,3,4,5,5,6]
sum(a,len())

Result:

TypeError: len() takes exactly one argument (0 given)

I'm unable to replicate it with Counter() (due to an error in pip while downloading collections package), nor am i able to find any documentation that mentions about giving functions as the start parameters.

Could anyone throw some light on this. Thanks

Upvotes: 0

Views: 97

Answers (2)

chepner
chepner

Reputation: 531808

Counter() provides an empty instance of Counter; len cannot be called with no arguments.

sum(counters, Counter()) is roughly equivalent to

result = Counter()
for x in counters:
    result = result + x

You can do this because addition is defined for instance of Counter.

For the example you are trying, you want as a starting value is the length of an empty list:

sum(a, len([]))

Since len([]) == 0, it's the same as sum(a, 0) or just sum(a).

Upvotes: 2

Karl Knechtel
Karl Knechtel

Reputation: 61615

My doubt is in the sum() which takes Counter() as the start parameter. What would happen in this case ?

Just as in any other case, it takes the initial Counter() and adds the first element of counters to it, then it adds the next one to that result, and so on. This is the same as if you had used the + symbol between all of the Counter instances explicitly. To understand what that does, see the documentation.

TypeError: len() takes exactly one argument (0 given)

Well, yes, like it says; len needs to know what to get the length of. I don't understand what you want this sum call to do.

nor am i able to find any documentation that mentions about giving functions as the start parameters.

collections.Counter isn't a function; it's a class. However, len(x) isn't a function either; it's the result of calling that function. (Similarly, the result of calling the collections.Counter class is a collections.Counter instance.) Anyway, it doesn't matter where the start parameter comes from; what matters is the value it has. For example:

a=[2,3,3,4,5,5,6]
sum(a,len(a))

a has 7 items in it, so len(a) is equal to 7, and the result is the same as writing sum(a, 7) directly. That is 7 + 2 + 3 + 3 + 4 + 5 + 5 + 6 = 35.

Upvotes: 2

Related Questions