1

I'm studying Python and am hitting some Pythonic oddity. I can't figure out why in returning, this function throws away data.

def foo(mylist=None):
    print "Input: {}".format(mylist)
    if mylist is None:
        mylist = list()
    if len(mylist) == 3:
        return mylist
    else:
        mylist.append(len(mylist))
        foo(mylist)

print "Output: {}".format(foo())

This prints:

Input: None
Input: [0]
Input: [0, 1]
Input: [0, 1, 2]
Output: None

I would guess that it has to do with pointing to a list that no longer exists, but I don't get that in a simpler example:

def simple_foo():
    to_return = [1, 2, 3]
    return to_return

print "Simple output: {}".format(simple_foo())

I've even tried (in foo) deep-copying my list into a to_return variable, then returning that, but that doesn't seem to work either. Can anybody shed some light on this? I would appreciate it.

1 Answer 1

8

You have to keep returning:

Your recursive call:

foo(mylist)

needs its return value returned:

return foo(mylist)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That's not even a Python thing; I should have caught that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.