1

The return of a python recusion differs and I do not understand why:

from bs4 import BeautifulSoup


def recurse_table(table, table_list):
    if table.find_next("table") is not None:
        recurse_table(table.find_next("table"), table_list)
    table_list.append(table)
    return table_list


fp = open("tc4400_cs_2.html")
soup = BeautifulSoup(fp.read(), features="html.parser")
print(len(recurse_table(soup.find("table"), [])))

returns correct length (4).

Whereas

from bs4 import BeautifulSoup


def recurse_table(table, table_list):
    if table.find_next("table") is not None:
        recurse_table(table.find_next("table"), table_list)
    return table_list.append(table)


fp = open("tc4400_cs_2.html")
soup = BeautifulSoup(fp.read(), features="html.parser")
print(len(recurse_table(soup.find("table"), [])))

returns TypeError: object of type 'NoneType' has no len()

What am I missing?

1 Answer 1

1

The return differs because what you're returning differs. The .append() method modifies table_list but does not return it, instead it returns a None. If you want to return the list, then you should append table to the list in one line and then in the next return the list, just like you already do in the first code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.