In this post we will be creating a Python script that will print the values within a list to a coloured table to output. To do this we will be using the ‘rich’ library which allows us to create aesthetically pleasing command line applications. The library is very useful whereby it allows formatting to many elements of output.
To install the rich library run the following command.
pip install rich
See our lists for this example below. List1 consists of a number of names and List2 contains their ages respectively.
List1=["Lionel Messi","Cristiano Ronaldo","Raheem Sterling","Kylian Mbappé","Mohamed Salah"] List2=[35,37,28,24,30]
See the snippet of Python code below where we print the list values above to a coloured table. In this example we have also assigned a table title. For a list of the standard colours available click here.
We start by defining our table and its title and then its column headings. We then move on to iterating over the values of our lists and add these as rows to our table before printing to output.
from rich.console import Console from rich.table import Table table = Table(title="Best Football Players") table.add_column("Name",style="cyan") table.add_column("Age", style="bright_green") List1=["Lionel Messi","Cristiano Ronaldo","Raheem Sterling","Kylian Mbappé","Mohamed Salah"] List2=[35,37,28,24,30] for name,age in zip(List1,List2): table.add_row(name,str(age)) console = Console() console.print(table)
An image of what this would look like whilst running can be seen below.
Take a look at some of our other content around the Python programming language by clicking here.