1

I had to write 2 bits of code to find the length of a list without using the len operator, one with a for loop and one using recursion. I'm having trouble with my recursion piece.

def list_length(list):
    sum=0
    if not list:
        print("The list is empty.")
        exit()
    if type(list) == type([]):
        for item in (list):
            sum+=1
        print("The length of the list is ",sum)

    else:
        print("The input is not a list.")
        exit()

my_list = [1,12,15,100];
list_length(my_list)



def recursive_length(list):
    sum=0
    if not list:
        print("The list is empty.")
        exit()
    if type(list) == type([]):
        if list:
            return 1 + recursive_length(list[1:])
            return 0
        print("The length of the list is ",sum)

    else:
        print("The input is not a list.")
        exit()

my_list = [13,12,1];
recursive_length(my_list)

The first method works as expected, but for my recursive method, the output is "The list is empty.", I should be getting "The length of the list is 3."

Timothy C.
  • 45
  • 6
  • 1
    What's wrong with `sum([1 for item in mylist])`? :-) – paxdiablo Oct 22 '19 at 03:46
  • 2
    The recursive solution will always eventually recieve an empty list. That's expected. That's called the "base case" of the recursion. Don't exit in that case. Think about what should be returned in the base case instead. – Carcigenicate Oct 22 '19 at 03:49

1 Answers1

0
def recursive_length(my_list):
    if not isinstance(my_list, list):
        raise ValueError("I can only determine the length of a list, sorry.")
    if not my_list:
        return 0

    return 1 + recursive_length(my_list[1:])
Mikhail Golubitsky
  • 590
  • 1
  • 8
  • 10