Suppose that we want to print a list element-by-element, one element per line. How to do that without loops?

Here's an idea. To print the list L, we need to first print L[0], and then print the rest of the list L[1:]. Let's implement this:

In [1]:
def print_list(L):
    '''Print the list L element-by-element, one element per line'''
    
    #Base case: do nothing for lists of length 0
    if len(L) == 0:
        return 
    
    print(L[0])
    print_list(L[1:])

Here is another way to think about this function: if we assume that print_list works as advertized in its docstring, then we can use it recursively. We print L[0], and then take a leap of faith by calling print_list(L[1:]) on the shorter list. If the base case is set up correctly, this will work.

Printing the list in reverse

Here is an idea for how to print a list in reverse: first, print L[1:] in reverse, and then print the first element of L, L[0]. This works: let's look at an example.

Suppose L = [1, 2, 3, 4].

Then the reversed version of L[1:] is [4, 3, 2], so that the reversed L[1:] with 1 at the end will in fact be the reversed L. This suggests that we can write print_reversed_list() with very minimal modifications to print_list:

In [2]:
def print_reverse_list(L):
    '''Pritn the list L element-by-element in reverse, one element per line'''
    
    if len(L) == 0:
        return
    
    print_reverse_list(L[1:])
    print(L[0])

Let's try both functions:

In [3]:
print_list([1, 2, 3, 4])
1
2
3
4
In [4]:
print_reverse_list([1, 2, 3, 4])
4
3
2
1