I believe that you're being confused by the *tail
part of the whole thing:
>>> items = [3,5,8,6,1,2,10]
>>> head, *tail = items
>>> head
3
>>> tail
[5, 8, 6, 1, 2, 10]
Now, what's happening is this, when you reach the end of the list, as in there's only one item in the list *tail
returns an empty list:
>>> items = [3]
>>> head, *tail = items
>>> head
3
>>> tail
[]
In that case, the function just returns the value of head
.
So, to explain your ternary statement, (True) if (condition) else (False)
:
head + sum(tail) if tail else head
Add the head the sum of the rest of the list. So sum
keeps breaking it down, and then finally hits the base case, which is, if there's only one item in the list, then return the item. This link will explain in more detail, how exactly this works.