Search code examples
pythonpython-3.xrecursionnonetype

Getting NoneType Error in a function that is supposed to return a string?


I am trying to extract the first letter of each string from a list of strings. I know I can do this using abstract list functions but I wanted to do it using structural recursion.

Consider the code below:

def acronym(los)
    if los != []:
        return los[0][0] + acronym(los[1:])

I get the following error:

builtins.TypeError: Can't convert 'NoneType' object to str implicitly

While I did some research on SOF about this error, I still don't understand why this function is supposed to return None, when los[0][0] is a string and acronym(los[1:]) also returns a string.

Any suggestions?


Solution

  • Each time acronym() calls itself, it does so with all but the first string in your list: los[1:].

    Eventually, when you're down to just one string in the list, "all but the first string" is no strings at all, so that inside the next call of acronym(), los is an empty list, and your if los != []: test fails.

    Since you don't explicitly return anything in that case, Python returns None implicitly, which can't be concatenated with the string you've built up:

    >>> "Hhay" + None
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: Can't convert 'NoneType' object to str implicitly