Printing Lists As Tabular Data In Python

Introduction

In the realm of working with data, Python is an excellent tool. With its wide array of libraries and frameworks, Python provides users with a huge collection of tools for working splendidly with data. A widespread activity in programming is the rendition of lists into tabular data. Whatever you may be working with, numbers, strings, or a mixture of both, Python offers several methods to make lists in a commendable form and print them in an organized way. In this detailed guide, we will study various methods that could help accomplish this, including plain text tables, PrettyTable, tabulate and pandas.

In this tutorial, we will see the various examples for printing lists as tabular data in Python.

1. Plain text tables

When simplicity and degree of customization are the main factors, making plain text tables is a simple way of doing it. Python's built-in string formatting abilities allow you to tabularize data easily. Using a mix of strings, loops and formatting you can print lists in a narrow and easily-readable form.

Let us see the code implementation below:

Code Implementation:

Output:

+ --------------- + --------------- + --------------- +
|    Column 1     |    Column 2     |    Column 3     |
+ --------------- + --------------- + --------------- +
|        1        |      Apple      |        5        |
+ --------------- + --------------- + --------------- +
|        2        |     Banana      |        8        |
+ --------------- + --------------- + --------------- +
|        3        |     Orange      |        3        |
+ --------------- + --------------- + --------------- +

Explanation:

  • The function 'print_plain_text_ table' accepts the names of tuples as input parameter 'data', each tuple contains three objects representing one row of data.
  • It constructs the header row of the table with centering alignment using string formatting, specifying columns names as "Column 1", "Column 2", and "Column 3".
  • A separator row is thus created with the + character for borders and - characters for alignment, and all column widths are set to 17 characters.
  • The separator and header rows are printed for visual distinction of the header from data rows.
  • It processes each tuple in the data list with one string formatting with centered alignment for each element.
  • For each formatted row it is printed, separating them with the separator row for a visually appealing tabular format.
  • Also, an example usage is presented, where the function is invoked with example data (1, 'Apple', 5), (2, 'Banana', 8), and (3, 'Orange', 3) showing how it can be applied to print plain text table with the same data.

2. PrettyTable:

The PrettyTable library streamlines the process of making tables which is visually appealing using text. It presents a convenient API for making tables using a wide range of formatting possibilities.

To use PrettyTable, you need to install it first:

Now, let's explore how to use PrettyTable to print lists as tabular data: All the items will be returned by calling of {functionName}.

Code Implementation:

Output:

+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
|    1     |   BMW    |    5     |
|    2     | Mercedes |    8     |
|    3     |  Ferrari |    3     |
+----------+----------+----------+

Explanation:

  • The 'PrettyTable' library is imported at the start and has been used as 'PrettyTable' throughout using the statement 'from prettytable import PrettyTable'.
  • The function is named print_pretty_table and it is passed with one argument which is data that must be a list of tuples representing the rows of tabular data.
  • Within the function, a 'PrettyTable' object named table is instantiated.
  • The table column names are set by the 'field_names' attribute, and the column headers "Column 1", "Column 2", and "Column 3" are used.
  • It then does a sequence for each tuple in the data list and adds the row using add_row method of PrettyTable object.
  • When the table is populated with data, the print function is employed to show the formatted table.
  • The example function usage is given beneath its declaration. In this case, the function is carried out using the sample data (1, 'BMW', 5), (2, 'Mercedes', 8), and (3, 'Ferrari', 3).
  • In this case, the function 'print_pretty_table' is specified to print a table with the PrettyTable library.

3. Tabulate:

The tabulate library is the other powerful module for tabular data formatting as well. It supports different types of input data, among which are lists, dictionaries and pandas DataFrames. To use tabulate, you can install it with the following command:

Now, let's see how to use tabulate to print lists as tabular data.

Code Implementation:

Output:

╒════════════╤════════════╤════════════╕
│   Column 1 │ Column 2   │   Column 3 │
╞════════════╪════════════╪════════════╡
│          1 │ Rose       │          5 │
├────────────┼────────────┼────────────┤
│          2 │ Jasmine    │          8 │
├────────────┼────────────┼────────────┤
│          3 │ Lotus      │          3 │
╘════════════╧════════════╧════════════╛

Explanation:

  • The code under consideration imports the tabulate function that comes from the tabulate library, which makes formatting of tabular data possible.
  • It specifies a function referred to as print_tabulated_data that only accepts one parameter, namely data, which is expected to be a list of tuples representing tabulated data.
  • In the function scope, the list of headers created that comprises of the column names "Column 1", "Column 2", and "Column 3".
  • The tabulate function is then called with three arguments: data, headers=True and tablefmt='fancy_grid'.
  • This function formats the data into tabular format using the headers specified and "fancy_grid" table format, which adds visual borders to the table.
  • The formatted table goes to the variable table.
  • The print function is used lastly to show the formatted table.
  • Beneath the function definition, an example of how the function is used but it will use some sample data such as (1, 'Rose', 5), (2, 'Jasmine', 8), and (3, 'Lotus', 3).
  • In this example how to use print_tabulated_data function which is the part of tabulate package for aesthetically producing tabular data is given.

4. Pandas:

When it comes to advanced data manipulation and investigation, particularly in dealing with large data, Pandas Library is the best choice. Pandas DataFrame is a 2-dimensional labeled data structure that 'Pandas' offer. It can be used to easily manage and to transform tabular data. To use pandas, you can install it with the following command:

Now, let's explore how to print lists as tabular data using 'pandas':

Code Implementation:

Output:

Column 1 Column 2  Column 3
0         1    Apple         5
1         2   Banana         8
2         3   Orange         3

Explanation:

  • The code provided imports the statement 'import pandas as pd' to have access to the 'pandas' library, which is strong in data manipulation and analysis operations in Python.
  • It specifies a function called 'print_pandas_table' that receives a single input referred to as data, which is expected to be a list of tuples for the tabular data representation.
  • Inside the function DataFrame 'df' named is created with pd.DataFrame(data, columns= ["Column 1", "Column 2", "Column 3"]).
  • A DataFrame is created from the given data via the use of 'pd.DataFrame() ' .
  • Columns argument determines the column names in the DataFrame.
  • Next, the print function is used to show the DataFrame, df.
  • Just under the definition of the print_pandas_table function, a demonstration of usage is given in the form (1, 'Apple', 5), (2, 'Banana', 5), (3, 'Orange', 8).
  • The following case shows the usage of the print_pandas_table function to print the table data in a structured way applying the pandas package.

Conclusion

In the present article, we have looked at the various methods to print lists as tables in Python. Starting from simple plain text tables to pretty elegant ones like PrettyTable, tabulate, and pandas, you can choose your tools based on your needs and preferences.

The suitable method to be selected is determined by aspects like the structure of your data, required customization of representation, and the need for additional features to do manipulation and analysis. Whether you just started with the programming or a seasoned developer already, learning these techniques will broaden your skill to show and work around with tabular data in Python.