It is pretty unusual for me to be coding in python, but I’m just following the course in my computer science class. I was coding a recursive list generator, essentially making a list with a given start and ending value of even numbers between them in the list.
In my interpreter, I received the following error.
return [start] + list_even(start + 1, end) TypeError: can only concatenate list (not "NoneType") to list
I don’t really know the nature of Python error messages yet, but I think this means that I’m attempting to something that isn’t listable (e.g. able to be put into a list). So, something that cannot be added to a list.
My code is pretty simple, though in real life I would never do this recursively.
def list_even(start, end):
if start > end:
return []
elif start % 2 == 0:
return [start] + list_even(start + 1, end)
else:
list_even(start + 1, end)
Everything looks in order. We have our definition, our if-statement, an else-if branch and a concluding else. Each of those cases have an return. Oh, wait. They don’t! Notice the else branch does not return a value, instead it just calls itself without returning. That’s the problem!
So, in short, I missed a return so a NoneType (e.g. null value) was returned during the previous call and it tried to append it on to the list. And clearly appending a null onto a list won’t work, only appending lists to lists works.