Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Print a List of List in Python?

#1
How to Print a List of List in Python?

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:



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

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:

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:

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!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!



https://www.sickgaming.net/blog/2020/05/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

[-]
Discord

[-]
Active Threads
Can the player have two animal crossings...
Last Post: Sellen
Today 02:58 AM
» Replies: 0
» Views: 2
(Indie Deal) Cozy Grove, Iceberg, The Cr...
Last Post: xSicKxBot
Today 02:47 AM
» Replies: 0
» Views: 1
Microsoft - Aliens: Fireteam Elite avail...
Last Post: xSicKxBot
Today 02:47 AM
» Replies: 0
» Views: 0
News - GamesMaster: Episode 2 Heaps Prai...
Last Post: xSicKxBot
Today 02:47 AM
» Replies: 0
» Views: 0
News - Stardew Valley Patch 1.5.5 Adds E...
Last Post: xSicKxBot
Today 02:47 AM
» Replies: 0
» Views: 0
(Indie Deal) Tales of Arise, Paradox, Ko...
Last Post: xSicKxBot
Yesterday 11:09 PM
» Replies: 0
» Views: 11
News - Looks Like Pokémon GO’s Next Seas...
Last Post: xSicKxBot
Yesterday 11:09 PM
» Replies: 0
» Views: 0
[Tut] How to Deploy a Smart Contract on ...
Last Post: xSicKxBot
Yesterday 03:57 PM
» Replies: 0
» Views: 16
(Indie Deal) Anime Giveaways, Nerf Legen...
Last Post: xSicKxBot
Yesterday 03:57 PM
» Replies: 0
» Views: 3
Microsoft - Optimize app performance at ...
Last Post: xSicKxBot
Yesterday 03:57 PM
» Replies: 0
» Views: 3

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com



Discord Server © SickGaming.net 2012-2021