avatarLiu Zuo Lin

Summary

The article presents four methods for printing tables in Python, ranging from manual hardcoded and dynamic approaches to using the Pandas and Tabulate libraries.

Abstract

The web content provides a comprehensive guide on how to print tables in Python, detailing both manual methods and library-based solutions. Initially, the author explains how to manually print a table by hardcoding the format, which is simple but not scalable for varying data lengths. The second method demonstrates a dynamic approach to printing tables that adjusts to the length of the data. The article then transitions to library-based methods, showcasing the Pandas library for its ability to create tables with minimal effort and the Tabulate library for its straightforward table formatting capabilities. The author emphasizes the practicality of using libraries over manual methods for efficiency and scalability, especially for larger datasets or professional applications.

Opinions

  • The author suggests that manual table printing in Python is primarily useful for practice rather than practical applications.
  • Pandas is highlighted as the preferred method for table creation due to its ease of use and automation, making it suitable for handling larger datasets.
  • The Tabulate library is recommended for its simplicity in formatting tables, which is beneficial for quick and clean data presentation.
  • The author encourages readers to support their work by engaging with their content through claps, comments, and highlights, as well as following them on social media and subscribing to their Medium account.
  • The article implies that while manual methods provide learning value, they are not recommended for serious projects where reliability and efficiency are crucial.

4 Ways To Print Tables in Python

Our table data

headers = ['fruit', 'price', 'country']

fruits = [
  ['apple', 4, 'sg'],
  ['orange', 5, 'sg'],
  ['pear', 6, 'sg'],
  ['pineapple', 7, 'sg'],
]

For simplicity’s sake, let’s use this data to print our tables

1) Manually in Python (Hardcoded)

headers = ['fruit', 'price', 'country']

fruits = [
  ['apple', 4, 'sg'],
  ['orange', 5, 'sg'],
  ['pear', 6, 'sg'],
  ['pineapple', 7, 'sg'],
]

for row in [headers]+fruits:
    for col in row:
        print(str(col).ljust(15), end='')
    print()

^ here, the .ljust(n) method creates a string of length n with whitespaces padded on the right.

Taking advantage of this, we can create a table where each column is of a predefined length. However, note that our table will break if any of our columns have a length longer than 15.

2) Manually in Python (Dynamic)

headers = ['fruit', 'price', 'country']
fruits = [
  ['apple', 4, 'sg'],
  ['orange', 5, 'sg'],
  ['pear', 6, 'sg'],
  ['pineapple', 7, 'sg'],
]

def table(headers, fruits):
    data = [headers]+fruits
    # first determine longest length in column
    N = []
    for i,_ in enumerate(headers):
        col = [row[i] for row in data]
        N.append(len(str(max(col, key=lambda x:len(str(x))))))
    # use longest length to print table
    for row in data:
        for i,col in enumerate(row):
            print(str(col).ljust(N[i]+2), end='')
        print()

table(headers, fruits)

^ here, we first determine the length of the longest element in each column.

  • for the fruit column, it’ll be pineapple which is 9
  • for the price column, it’ll be price itself
  • for the country column, it’ll also be country itself

We then use these numbers + 2 (or however much you wish to add) to determine the best length for each table column.

headers = ['fruit', 'price', 'country']
fruits = [
  ['apple', 4, 'sg'],
  ['orange', 5, 'sg'],
  ['pear', 6, 'sg'],
  ['pineapple juice', 7, 'sg'],
]

def table(headers, fruits):
   # same stuff above

table(headers, fruits)

^ notice that having longer values no longer break the table, and the table column length expands together with our values.

But why do this manually in Python ourselves when we can simply import a library to do this for us? (other than practice purposes)

3) Using Pandas

Install pandas using pip install pandas if you haven’t already

headers = ['fruit', 'price', 'country']
fruits = [
  ['apple', 4000000, 'sg'],
  ['orange', 5, 'sg'],
  ['pear', 6, 'sg'],
  ['pineapple juice', 7, 'sg'],
]

import pandas as pd

df = pd.DataFrame(fruits, columns=headers)
print(df)

^ here, Pandas helps us to automatically create a table without us having to do much work — we simply need to tell Pandas what are our headers (in Pandas this is called columns) and what is our data.

4) Using Tabulate

Do install this using pip install tabulate if you haven’t already

headers = ['fruit', 'price', 'country']
fruits = [
  ['apple', 4000000, 'sg'],
  ['orange', 5, 'sg'],
  ['pear', 6, 'sg'],
  ['pineapple juice', 7, 'sg'],
]

from tabulate import tabulate

table = tabulate(fruits, headers=headers)
print(table)

^ similarly, tabulate helps us to automatically create and format a table — we simply need to pass our data and headers to the tabulate function to do all the work for us.

Conclusion

It’s probably not a good idea to create your own tables manually unless you’re doing it to practice your programming skills. My favourite here would probably be Pandas

If You Wish To Support Me As A Creator

  1. Clap 50 times for this story
  2. Leave a comment telling me your thoughts
  3. Highlight your favourite part of the story

Thank you! These tiny actions go a long way, and I really appreciate it!

YouTube: https://www.youtube.com/@zlliu246

LinkedIn: https://www.linkedin.com/in/zlliu/

My Ebooks: https://zlliu.co/ebooks

Python
Tech
Technology
Programming
Coding
Recommended from ReadMedium