Python print list of lists as table

I have this list of lists:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

that i have to transform into this table:

apples      Alice    dogs
oranges       Bob    cats 
cherries    Carol    moose 
banana      David    goose

The trick for me, is have the "lines" to be converted into columns [i.e. apples, oranges, cherries, banana under same column]

I have tried different options [A]:

for row in tableData:
        output = [row[0].ljust[20]]
            for col in row[1:]:
             output.append[col.rjust[10]]
            print[' '.join[output]]

option [B]:

method 2

for i in tableData:
    print[ i[0].ljust[10]+[str[i[1].ljust[15]]]+[str[i[2].ljust[15]]]+
    [str[i[3].ljust[15]]]]    

None seems to address the issue.
Thanks in advance for any suggestions.

Short answer: To print a list of lists in Python without brackets and aligned columns, use the ''.join[] function and a generator expression to fill each string with enough whitespaces so that the columns align:

# Create the list of lists
lst = [['Alice', 'Data Scientist', '121000'],
       ['Bob', 'Java Dev', '99000'],
       ['Ann', 'Python Dev', '111000']]


# Find maximal length of all elements in list
n = max[len[x] for l in lst for x in l]

# Print the rows
for row in lst:
    print[''.join[x.ljust[n + 2] for x in row]]

I’ll explain this code [and simpler variants] in the following video:

How to Print a List of List in Python?

As an exercise, you can also try it yourself in our interactive shell:

  • Step-By-Step Problem Formulation
  • Print List of Lists With Newline
  • Print List of Lists Without Brackets
  • Print List of Lists Align Columns
  • Print List of Lists with Pandas
  • Where to Go From Here?

Step-By-Step Problem Formulation

Do you want to print a list of lists in Python so that the format doesn’t look like a total mess? In this tutorial, I’ll show you how to orderly print a list of lists in Python—without using any external library.

Before you start to think about the solution, you should understand the problem. What happens if you print a list of lists? Well, let’s try:

lst = [['Alice', 'Data Scientist', 121000],
       ['Bob', 'Java Dev', 99000],
       ['Ann', 'Python Dev', 111000]]
print[lst]

The output is not very nice:

[['Alice', 'Data Scientist', 121000], ['Bob', 'Java Dev', 99000], ['Ann', 'Python Dev', 111000]]

Instead, you’d would at least want to see a beautiful output like this one where each row has a separate line and the rows are aligned:

[['Alice', 'Data Scientist', 121000], 
 ['Bob', 'Java Dev', 99000], 
 ['Ann', 'Python Dev', 111000]]

And maybe, you even want to see an output that aligns the three columns as well like this one:

Alice           Data Scientist  121000          
Bob             Java Dev        99000           
Ann             Python Dev      111000   

I’ll show you all those different ways of printing a list of lists next. So let’s start with the easiest one:

Print List of Lists With Newline

Problem: Given a list of lists, print it one row per line.

Example: Consider the following example list:

lst = [[1, 2, 3], [4, 5, 6]]

You want to print the list of lists with a newline character after each inner list:

1 2 3
4 5 6

Solution: Use a for loop and a simple print statement:

lst = [[1, 2, 3], [4, 5, 6]]

for x in lst:
    print[*x]

The output has the desired form:

1 2 3
4 5 6

Explanation: The asterisk operator “unpacks” all values in the inner list x into the print statement. You must know that the print statement also takes multiple inputs and prints them, whitespace-separated, to the shell.

Related articles:

  • Unpacking Operator *
  • How to Print a List Beautifully
  • Python Lists of Lists

Print List of Lists Without Brackets

To print a list of lists without brackets, use the following code again.

Solution: Use a for loop and a simple print statement:

lst = [[1, 2, 3], [4, 5, 6]]

for x in lst:
    print[*x]

The output has the desired form:

1 2 3
4 5 6

But how can you print a list of lists by aligning the columns?

Print List of Lists Align Columns

Problem: How to print a list of lists so that the columns are aligned?

Example: Say, you’re going to print the list of lists.

[['Alice', 'Data Scientist', 121000], 
 ['Bob', 'Java Dev', 99000], 
 ['Ann', 'Python Dev', 111000]]

How to align the columns?

Alice   'Data Scientist',  121000], 
 Bob    'Java Dev',           99000], 
 Ann    'Python Dev',      111000]]

Solution: Use the following code snippet to print the list of lists and align all columns [no matter how many characters each string in the list of lists occupies].

# Create the list of lists
lst = [['Alice', 'Data Scientist', '121000'],
       ['Bob', 'Java Dev', '99000'],
       ['Ann', 'Python Dev', '111000']]


# Find maximal length of all elements in list
n = max[len[x] for l in lst for x in l]

# Print the rows
for row in lst:
    print[''.join[x.ljust[n + 2] for x in row]]

The output is the desired:

Alice           Data Scientist  121000          
Bob             Java Dev        99000           
Ann             Python Dev      111000   

Explanation:

  • First, you determine the length n [in characters] of the largest string in the list of lists using the statement max[len[x] for l in lst for x in l]. The code uses a nested for loop in a generator expression to achieve this.
  • Second, you iterate over each list in the list of lists [called row].
  • Third, you create a string representation with columns aligned by ‘padding’ each row element so that it occupies n+2 characters of space. The missing characters are filled with empty spaces.

You can see the code in action in the following memory visualizer. Just click “Next” to see which objects are created in memory if you run the code in Python:

Related articles: You may need to refresh your understanding of the following Python features used in the code:

  • List comprehension and generator expressions
  • String join[]
  • Printing lists

Print List of Lists with Pandas

Last but not least, I’ll show you my simple favorite: simply import the pandas library [the excel of Python coders] and print the DataFrame. Pandas takes care of pretty formatting:

lst = [['Alice', 'Data Scientist', '121000'],
       ['Bob', 'Java Dev', '99000'],
       ['Ann', 'Python Dev', '111000']]

import pandas as pd
df = pd.DataFrame[lst]
print[df]

The output looks beautiful—like a spreadsheet in your Python shell:

       0               1       2
0  Alice  Data Scientist  121000
1    Bob        Java Dev   99000
2    Ann      Python Dev  111000

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

How do I turn a list into a table in Python?

How to Easily Create Tables in Python.
install tabulate. We first install the tabulate library using pip install in the command line: pip install tabulate..
import tabulate function. ... .
list of lists. ... .
dictionary of iterables. ... .
missing values..

How do you print a list inside a list in Python?

Using the * symbol to print a list in Python. To print the contents of a list in a single line with space, * or splat operator is one way to go. It passes all of the contents of a list to a function. We can print all elements in new lines or separated by space and to do that, we use sep=”\n” or sep=”, ” respectively.

Can you make a list of lists in Python?

Python provides an option of creating a list within a list. If put simply, it is a nested list but with one or more lists inside as an element. Here, [a,b], [c,d], and [e,f] are separate lists which are passed as elements to make a new list. This is a list of lists.

How do you print a column of elements in a list in Python?

Use str..
print[a_table].
length_list = [len[element] for row in a_table for element in row] Find lengths of row elements..
column_width = max[length_list] Longest element sets column_width..
for row in a_table:.
row = "". join[element. ... .
print[row].

Chủ Đề