if current_list != toc:
    toc.append(current_list)

def list_to_html(lst):
    result = ['<ul>']
for item in lst:
    if isinstance(item, list):
        result.append(list_to_html(item))
else:
    result.append('<li><a href="#%s">%s</a></li>' % item)
result.append('</ul>')
return '\n'.join(result)
print(list_to_html(toc))
print(soup)
Generate a table of contents from HTML with Python