In this post we will be creating a Python script that will print lists in tabulated form to output. To do this we will be using the ‘prettytable‘ library, used for displaying tabular data in a visually appealing format.
To install the prettytable library run the following command.
pip install prettytable
See below our two lists for this example, one of which containing first names and the other containing last names.
Firstnames=['Harry', 'Ron', 'Tom', 'Dracoy'] Lastnames=['Potter', 'Weasley', 'Riddle', 'Malfoy']
See the snippet of Python code below where we utilise the prettytable library to print our lists in tabulated form.
Using a for loop we iterate through both lists and add each item as an entry to our pretty table.
from prettytable import PrettyTable Firstnames=['Harry', 'Ron', 'Tom', 'Dracoy'] Lastnames=['Potter', 'Weasley', 'Riddle', 'Malfoy'] t = PrettyTable(['Firstname', 'Lastname']) for first, last in zip(Firstnames, Lastnames): t.add_row([first,last]) print(t)
The above would return the following as output.
+-----------+----------+ | Firstname | Lastname | +-----------+----------+ | Harry | Potter | | Ron | Weasley | | Tom | Riddle | | Dracoy | Malfoy | +-----------+----------+ >>>
Take a look at some of our other content around the Python programming language by clicking here.