-2

Here is a recursive function in python3. I have a feeling that I do not fully understand the if else logic in return statement.

items = [3,5,8,6,1,2,10]

def sum(items):
    head, *tail = items
    return head + sum(tail) if tail else head

Please explain what is going on in return statement.

minerals
  • 6,090
  • 17
  • 62
  • 107

1 Answers1

3

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.

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
  • Thanks, I was confused by `return {var} if A else B` syntax, looks quite puzzling when used on one line together with return. – minerals Jan 21 '14 at 09:13