Why my function does not return the list?

Question:

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)
Asked By: Peepogeek

||

Answers:

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]
Answered By: funnydman
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.