0

I have a function that modifies a list, however it doesn't return anything. It is a long function but to give an example, the following has the same problem. Why is it not returning anything?

def inventedfunction(list1):
    list2=list1[:-1]
    if len(list2)!=1:
        inventedfunction(list2) 
    else:
        return list2  
2
  • 1
    Because inventedfunction(list2) means 'call inventedfunction on list2, but discard its result'. I guess you need return inventedfunction(list2) Commented Aug 17, 2015 at 4:22
  • How could I avoid this problem supposing I need to use recursion in this example? Commented Aug 17, 2015 at 4:23

2 Answers 2

2

Replace inventedfunction(list2) with return inventedfunction(list2). If you just call it without the return statement, the result is thrown out.

Working code:

def inventedfunction(list1):
    list2=list1[:-1]
    if len(list2)!=1:
        return inventedfunction(list2) 
    else:
        return list2 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. How about if I need after running inventedfucntion(somelist) to modify the input list (somelist)?
Do somelist = inventedfunction(somelist)
0

You didn't say what the function is supposed to do, so I am assuming that "inventedfunction" means "inverted function". Even if this is not correct, the idea is the same. If this is not the case or you don't understand then post back with more info.

You don't catch any of the returns, and don't return anything (None) if len(list2) != 1. You also would have to create a 2nd list to hold the numbers removed from the list sent to the function, and return the updated list as well according to way your code is structured.

def inventedfunction(list1, new_list=[]):
    ## at the least add print statements so you know what is happening
    print new_list, "----->",  list1
    list2=list1[:-1]
    new_list.append(list1[-1])  ## append item removed from list1 --> list2
    if len(list2):
        new_list, list2=inventedfunction(list2)
    return new_list, list2  ## both updated lists returned

print inventedfunction([1, 2, 3, 4, 5])

Comments

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.