calculate length of list recursively

Question:

If you have a list = [1,2,3,4,5]

how would you recursively calculate the length of that list without using len(list)?

myarray = [1,2,3,4,5]

def mylist(myarray):
    if (myarray == []):
        print ("The list is empty")
        return 
    return 1 + ?

Don’t want to use len but just add 1 each time there exists a value in list. How would I do that?

Asked By: Eric

||

Answers:

Use a recursive function.

Basically call the function again and add the count returned by it to the result. Important thing is to make sure you exit (return) when the function has nothing to do.

Check out this post
Python recursion and return statements

Answered By: Devraj
>>> def list_length(L):
...     if L:
...         return 1 + list_length(L[1:])
...     return 0
... 
>>> list_length(myarray)
5
>>> list_length([])
0
>>> list_length([1]*4)
4
>>> 

If the list has elements, return 1 + the length of the list minus one element.

You can do this a couple different ways, but slicing [:1] or [1:] will give you the elements minus the last or first respectively, makes sense.

If the list has no elements, return 0

Answered By: dting
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.