Use tabulate

from tabulate import tabulate

table = [['one','two','three'],['four','five','six'],['seven','eight','nine']]

print(tabulate(table, tablefmt='html'))

Which produces the following output.

<table>
<tbody>
<tr><td>one  </td><td>two  </td><td>three</td></tr>
<tr><td>four </td><td>five </td><td>six  </td></tr>
<tr><td>seven</td><td>eight</td><td>nine </td></tr>
</tbody>
</table>
Answer from Tomasz on Stack Overflow
Top answer
1 of 7
56

Use tabulate

from tabulate import tabulate

table = [['one','two','three'],['four','five','six'],['seven','eight','nine']]

print(tabulate(table, tablefmt='html'))

Which produces the following output.

<table>
<tbody>
<tr><td>one  </td><td>two  </td><td>three</td></tr>
<tr><td>four </td><td>five </td><td>six  </td></tr>
<tr><td>seven</td><td>eight</td><td>nine </td></tr>
</tbody>
</table>
2 of 7
42

I would decompose your problem into two parts:

  • given a "flat list", produce a list of sublists where the sublists are of a given length and the overall list may be walked into either a "row major" order (your first and third example) or "column major" (your second example);
  • given a list of sublists with string items, produce an HTML table out of it.

I think the two tasks are really very distinct and there's nothing to gain (and much to lose) in mushing them up, so I would be astonished if any well-designed library did such mushing.

For point 1, row-major is easy:

def row_major(alist, sublen):      
  return [alist[i:i+sublen] for i in range(0, len(alist), sublen)]

and column-major not that bad:

def col_major(alist, sublen):
  numrows = (len(alist)+sublen-1) // sublen 
  return [alist[i::sublen] for i in range(numrows)]

for example...:

L = ['one','two','three','four','five','six','seven','eight','nine']
for r in row_major(L, 3): print r
print
for r in col_major(L, 3): print r
for r in row_major(L, 4): print r

produces your three desired results (one list per row, not in HTML form yet;-).

The second half of the problem -- produce an HTML table from a list of lists of strings:

def html_table(lol):
  print '<table>'
  for sublist in lol:
    print '  <tr><td>'
    print '    </td><td>'.join(sublist)
    print '  </td></tr>'
  print '</table>'

If you want to get it as a single string rather than print it out, change each print into yield and use '\n'.join(html_table(lol)).

Now you have two simple, useful, usable and reusable building blocks -- having them separate will come in handy whenever you want to present your data as anything BUT an HTML table, and also whenever the list-of-lists to present as an HTML table comes from any other way of building it. Putting them together is easy to do in your application code, but of course it's also easy to do a simple "glue routine", e.g., assuming the yield-based version of html_table and that a single string result is desired:

def list_to_html_table(alist, sublength, column_major=False):
  if column_major:
    lol = col_major(alist, sublength)
  else:
    lol = row_major(alist, sublength)
  return ''.join(html_table(lol))

Isn't this building-blocks approach really nicer and more pleasant, as well as more productive, than programming in terms of big blobs of mushed-up glue...?-)

🌐
W3Schools
w3schools.com › html › html_tables.asp
HTML Tables
3 weeks ago - Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
People also ask

What kind of data can HTML tables contain?

HTML tables can contain a wide variety of data types. They are commonly used to display structured information such as text, numbers, dates, images, links, and even nested tables. This makes them suitable for representing data like financial reports, product listings, and statistical data – which we can then scrape for analysis.

🌐
scraperapi.com
scraperapi.com › home › blog › how to scrape html tables using python
How To Scrape HTML Tables Using Python
What are the best tools to scrape HTML tables?

Some of the best tools for scraping HTML tables include Python libraries like BeautifulSoup and Pandas. These tools allow you to easily extract table data and manipulate it. For more complex scenarios, Scraping APIs like ScraperAPI can handle dynamic content and bypass anti-scraping measures.

🌐
scraperapi.com
scraperapi.com › home › blog › how to scrape html tables using python
How To Scrape HTML Tables Using Python
How Can I Scrape Dynamic Tables?

To scrape dynamic tables that are generated or updated using JavaScript, you need tools that can render JavaScript content. Tools like ScraperAPI can fetch the fully loaded page, allowing you to extract the dynamic table data. Alternatively, you can use webdrivers like Selenium or PlayWright, which can simulate a real user interacting with the browser, loading dynamic content before scraping.

🌐
scraperapi.com
scraperapi.com › home › blog › how to scrape html tables using python
How To Scrape HTML Tables Using Python
🌐
PyPI
pypi.org › project › pretty-html-table
pretty-html-table · PyPI
padding - accepts a string to set the CSS padding in the table (10px, 0px 20px, 0px 20px 0px 0px) odd_bg_color - accepts a hex or standard color for the odd row background · border_bottom_color - accepts a color for the bottom border for the headers · html_table = build_table(df , 'yellow_dark' , font_size='medium' , font_family='Open Sans , sans-serif' , text_align='left' , width='auto' , index=False ,conditions={ 'Age': { 'min': 25, 'max': 60, 'min_color': 'red', 'max_color': 'green', } } , even_color='black' , even_bg_color='white')
      » pip install pretty-html-table
    
Published   Apr 25, 2022
Version   0.9.16
🌐
Tchut-Tchut Blog
beenje.github.io › blog › posts › parsing-html-tables-in-python-with-pandas
Parsing HTML Tables in Python with pandas | Tchut-Tchut Blog
March 27, 2018 - Let's import this HTML table in a DataFrame. Note that the function read_html always returns a list of DataFrame objects: ... [ Programming Language Creator Year 0 C Dennis Ritchie 1972 1 Python Guido Van Rossum 1989 2 Ruby Yukihiro Matsumoto 1995]
🌐
ScraperAPI
scraperapi.com › home › blog › how to scrape html tables using python
How To Scrape HTML Tables Using Python
March 31, 2026 - This is why this is a great page to practice scraping tabular data with Python. There’s a clear <table> tag pair opening and closing the table and all the relevant data is inside the <tbody> tag.
🌐
Esri Community
community.esri.com › t5 › geoprocessing-questions › python-table-to-html › td-p › 634710
Python Table to HTML - Esri Community
August 19, 2010 - # --------------------------------------------------------------------------- # TableToHtml.py # --------------------------------------------------------------------------- import sys, string, os, arcgisscripting gp = arcgisscripting.create(9.3) tablePath = gp.GetParameterAsText(0) filePath = gp.GetParameterAsText(1) outfile = open(filePath, "w") fields = gp.ListFields(tablePath) fieldNames = [] for field in fields: if (field.type <> "Geometry" and field.type <> "BLOB"): fieldNames.append(field.name) outfile.write("<table border=""1"">\n") outfile.write("<tr>\n") for fieldName in fieldNames: o
Find elsewhere
🌐
Reddit
reddit.com › r/python › guide to scrape html table using python
r/Python on Reddit: Guide to Scrape HTML Table Using Python
October 29, 2022 - Yeah...I stopped reading the second they equated <th> and <thead>, and then described them as defining a row. My man, have you ever created an HTML table? Edit: Here's a nice W3Schools refresher. ... Help required regarding both web scraping and using pandas to store data from a table in csv using python
🌐
Reddit
reddit.com › r/learnpython › what is a good way of generating interactive tables with python for a standalone html output?
r/learnpython on Reddit: What is a good way of generating interactive tables with Python for a standalone html output?
July 8, 2022 -

Hello

So, I come primarily from R programming and there, I relied heavily on the {reactable} package to create interactive tables and generate an html output with R Markdown. Some examples from the main gallery are this one (note that the rows are expandable) and this (possibility to add images and plots to each row). reactable relies on React Table from React.

In Python, from what I've seen so far, I could use Quarto to replace R Markdown in generating html reports, but I still couldn't find a way to create flexible, interactive tables such as the ones above. I even found this related question here on Reddit, but the replies didn't help me.

Do you have any suggestions on which would be the best way to deal with this? I suspect that perhaps I won't find a solution purely in Python, but maybe even some "indirect" solution requiring a little JS would work well for my use case

Thank you!

🌐
Practical Business Python
pbpython.com › pandas-html-table.html
Reading HTML tables with Pandas - Practical Business Python
Taking care of business, one python script at a time · Mon 14 September 2020 · Posted by Chris Moffitt in articles · The pandas read_html() function is a quick and convenient way to turn an HTML table into a pandas DataFrame.
🌐
Scott Rome
srome.github.io › Parsing-HTML-Tables-in-Python-with-BeautifulSoup-and-pandas
Parsing HTML Tables in Python with BeautifulSoup and pandas
May 30, 2016 - In the next bit of code, we define a website that is simply the HTML for a table. We load it into BeautifulSoup and parse it, returning a pandas data frame of the contents. As you can see, we grab all the tr elements from the table, followed by grabbing the td elements one at a time. We use the “get_text()” method from the td element (called a column in each iteration) and put it into our python object representing a table (it will eventually be a pandas dataframe).
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Learn_web_development › Core › Structuring_content › HTML_table_basics
HTML table basics - Learn web development | MDN
We've talked table theory enough, so, let's dive into a practical example and get you to build up a simple table. First of all, make a copy of blank-template.html and minimal-table.css in a new directory on your local machine.
🌐
Python Software Foundation
wiki.python.org › psf › HelpOnTables.html
Table Markup - Python Wiki
If a change to this archive is absolutely needed, requests can be made via the infrastructure@python.org mailing list. ... Bulleted lists and other complex content within cells To create a table, start & end a new line using the table marker; two 'pipe' characters "||".
🌐
Plotly
dash.plotly.com › dash-html-components › table
html.Table - Dash for Python Documentation
A Table component. Table is a wrapper for the <table> HTML5 element. For detailed attribute info see: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table · Access this documentation in your Python terminal with: ```python
🌐
Medium
kumudithaudaya.medium.com › display-a-table-in-a-database-in-html-using-prettytable-python-70d7325f2e46
Display a table in a database in HTML using prettytable python | by Kumuditha Karunarathna | Medium
May 6, 2021 - Now to turn “mytable” into an HTML table we can use get_html_string() method to generate the HTML code and assign it to a variable “htmlCode” · And at this point, if you print “htmlCode” the HTML code will be printed.
🌐
DZone
dzone.com › coding › languages › how to use python to loop through html tables and scrape tabular data
Using Python to Loop Through HTML Tables
September 28, 2022 - Iterating through HTML tables is tricky, so we've created this guide to help you understand how to use Python to extract tabular data from public HTML tables.
🌐
Bright Data
brightdata.com › blog › web-data › how-to-scrape-html-tables
Guide on How to Scrape HTML Tables With Python
September 16, 2025 - This table has headers with the <th> tags, and rows are defined by <tr> tags with each <tr> representing a new horizontal row in the table. Inside each <tr>, the <td> tag creates individual cells within that row, holding the data displayed in each cell. Note: Before doing any scraping, it’s important that you review and abide by the website’s privacy policy and terms of service to ensure you follow all restrictions on data usage and automated access. To send an HTTP request and access the web page, create a Python file (eg html_table_scraper.py) and import the requests, BeautifulSoup, and pandas packages:
🌐
Python documentation
docs.python.org › 3 › library › stdtypes.html
Built-in Types — Python 3.14.6 documentation
In the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s (for example, bytearray only accepts integers that meet the value restriction ...
🌐
DEV Community
dev.to › chrisgreening › effortlessly-scrape-html-tables-into-python-using-pdreadhtml-559p
Effortlessly scrape HTML tables into Python using pd.read_html! - DEV Community
August 24, 2023 - pd.read_html is a function within pandas, a popular data manipulation library in Python. Its purpose is to scrape an HTML page (either from a URL or as a string) and extract all the table's found on the page
🌐
PyPI
pypi.org › project › simple-html-table
simple-html-table · PyPI
July 22, 2023 - Tags html , table · Requires: ... support for rowspan and colspan attributes. simple_html_table defines three classes that represent HTML tables, rows and cells respectively....
      » pip install simple-html-table
    
Published   Jul 26, 2023
Version   0.2.0
🌐
PyPI
pypi.org › project › html-table-extractor
html-table-extractor · PyPI
HTML Table Extractor is a python library that uses Beautiful Soup to extract data from complicated and messy html table
      » pip install html-table-extractor
    
Published   May 01, 2020
Version   1.4.1