Python: function always returns None

I have Python code that looks something like this:

my_start_list = ... def process ( my_list ): #do some stuff if len(my_list) > 1: process(my_list) else: print(my_list) return my_list print(process(my_start_list)) 

The strange thing is: print (my_list) displays the correct content. However, the second print statement that prints the return value of the function always prints "No." Even if I replace the normal return statement with return ("abc") , it is still None.

Since the contents of the variable seem to be valid on the same line before the return statement, I don’t know where to start debugging. Are there any common problems that can cause this?

+6
source share
4 answers

Here's what happens:

  • You call process(my_start_list) .
  • In the function, the if block is executed if len(my_list) > 1 , and there is no return statement.
    Here, since the else not executed, and since this is the only place you have a return clause, you return the default value of None .
  • If you have 0 or 1 element in the list, you return this list.

So, return the list returned by process(my_list)
I.e:

 def process(my_list): #do some stuff ... if len(my_list) > 1: return process(my_list) else: print(my_list) return my_list 
+8
source

You return a list only if it has 1 or 0 elements (base case). You need a return statement in the first block, where you make a recursive call, otherwise you go to the base register, return a list of length-1 to the next level and then return None rest of it up. So you want to look like this:

 def process(my_list): # Do some stuff. if len(my_list) > 1: return process(my_list) #If you don't return this result, you return None else: print(my_list) return my_list 

Now each case (and not just the base case) has a return value, so the return value will be distributed completely until your initial call.

+10
source

You call process recursively, but you never ignore its return value when you do this. Add a return to pass the return value:

 def process ( my_list ): #do some stuff if len(my_list) > 1: return process(my_list) else: print(my_list) return my_list 

Now that len(my_list) > 1 is True , you are actually passing the return value of the recursive call.

+3
source

As others have pointed out, you are missing the return .

I would personally turn this tail recursion into an iteration:

 def process(my_list): while True: # do some stuff if len(my_list) <= 1: return my_list 

I think this makes the intention a little clearer and also avoids the errors associated with tail recursion .

+2
source

All Articles