0

The strangest thing is that I place a print() just before the return and the print does give the values I expect, but then I receive None.

class listNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

a = listNode(1)
b = listNode(2)
c = listNode(4)

def convert_to_list_rec(nod, list=[]):
    if nod == None:
        print(list)
        return list
    list.append(nod.val)
    convert_to_list_rec(nod.next, list)


arr = convert_to_list_rec(a)
quamrana
  • 37,849
  • 12
  • 53
  • 71
Peepogeek
  • 25
  • 3
  • 4
    Did you mean: `return convert_to_list_rec(nod.next, list)`? I think this should be the last line of your recursive function. – quamrana Aug 09 '22 at 20:46
  • 1
    `list` is a reserved word and it looks like you're using it as a variable name? I suspect you're running into a conflict between the system definition of list (a class) and your presumed use of `list` as a variable name. I would rename `list` to something else. – David Parks Aug 09 '22 at 20:49
  • Can someone close this as a [duplicate](https://stackoverflow.com/questions/17778372/why-does-my-recursive-function-return-none)? – quamrana Aug 09 '22 at 20:50
  • 3
    Using a `list` as a variable name will just give you a headache. And setting a mutable list as an function default argument [will do it even more so](https://docs.python-guide.org/writing/gotchas/). – alex Aug 09 '22 at 20:50
  • 1
    Also, it's a bad idea to rely on recursion in python. This probably should be a simple iteration. – Kenny Ostrom Aug 09 '22 at 20:59

1 Answers1

2

You need to return from the recursive call, see this example:

class listNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


a = listNode(1)
a.next = listNode(2)
a.next.next = listNode(4)


def convert_to_list_rec(nod, res):
    if not nod:
        return res
    return convert_to_list_rec(nod.next, res + [nod.val])


arr = convert_to_list_rec(a, [])

print(arr)

Output:

[1, 2, 4]
funnydman
  • 9,083
  • 4
  • 40
  • 55