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."