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

2
  • 3
    -1 Was the title a question, or an order? Commented Jan 21, 2014 at 8:38
  • 1
    recursive, adj: See recursive. Commented Jan 21, 2014 at 8:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I was confused by return {var} if A else B syntax, looks quite puzzling when used on one line together with return.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.