Sometimes itβs easier for me to think about recursion by simply creating a list of calls that need to be made in a specific order. As the function continues, it creates a bunch of calls until it finally gets into the base register. The main case is a situation when further program splitting is not required; in this function, the base register is when there is nothing to print, in which case we simply leave without any action with return .
Cool stuff usually happens on the way back when we unwind a recursive stack of function calls. Currently, print_backward is called for each item in the list, and now it is "unwound", ending the most recent calls first and the previous ones last. This means that the " print_backward " instance created when you call it on the last item is the first to be completed, and thus the last item is the first to be printed, and then second to last, from third to last, etc., until the final function completes.
Take a look at this view of what happened:
print_backward(node1) #first call to print_backward print_backward(node2) #calls itself on next node print_backward(node3) #calls itself on next node print_backward(None) #calls itself on None. We can now start unwinding as this is the base case: print Node3 #now the third invocation finishes... print Node2 #and the second... print Node1 #and the first.
While the function is called first on earlier elements, the part that actually prints this element comes after the recursive call, so it will not actually be executed until the recursive call ends. In this case, this means that part of the print list will not be executed until all later items are printed first (in reverse order), so you get the items in the list printed back .: D
source share