lb_so
lb_so

Reputation: 146

[] parameter or input used in sum() function - what is it doing?

I am looking at the following page by a regular stackoverflow user, Peter Norvig, here: http://norvig.com/sudoku.html

In this code, Peter has used the following code:

peers = dict((s, set(sum(units[s], [])) - set([s])) for s in squares)

units is a dictionary of 'columns', 'rows' and '9*9 squares' on the sudoku board and squares is all possible row/column combinations.

I don't understand the sum notation sum(units[s], []) If I remove the , [] phrase I get an error:

"unsupported operand type(s) for +: 'int' and 'list'"

Using help(sum) returns

sum(iterable, start=0, /)

Return the sum of a 'start' value (default: 0) plus an iterable of numbers

When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types.

So my question is, "what is the [] doing in this function?" Obviously it's an empty list, but is it a parameter of the sum() function or is it a value to add to units[s] ? The python documentation is relatively 'quiet' on this, unless I'm simply not understanding it.... https://docs.python.org/3/library/functions.html#sum

Upvotes: 3

Views: 469

Answers (2)

ForceBru
ForceBru

Reputation: 44878

is it a parameter of the sum() function or is it a value to add to units[s]?

It's both: you pass it as a parameter to the function, which then does its own business and, as per the docs, "return[s] the sum of a 'start' value plus an iterable of numbers", that is:

sum([1,2,3,4,5], start) == start + 1 + 2 + 3 + 4 + 5

Some other types other than numbers support addition as well, such as lists:

[] + [1] + [2,3] == [1, 2, 3]

Upvotes: 4

rdas
rdas

Reputation: 21285

Sum uses the + operator for summation. + is overloaded in lists for extending lists

>>> sum([[1,2], [3,4], [5,6]], [])
[1, 2, 3, 4, 5, 6]

So sum(units[s], []) is trying to concat a list of iterables (units[s]) into a list .

You're getting that error probably because, units[s] is an integer for some reason, while it's supposed to be a list

Upvotes: 5

Related Questions