[Tut] How to Print a List of List in Python? - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Print a List of List in Python? (/thread-94842.html) |
[Tut] How to Print a List of List in Python? - xSicKxBot - 05-02-2020 How to Print a List of List in Python? <div><p><strong>Short answer: To print a list of lists in Python without brackets and aligned columns, use the <code>''.join()</code> function and a generator expression to fill each string with enough whitespaces so that the columns align:</strong></p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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))</pre> <p>I’ll explain this code (and simpler variants) in the following video:</p> <figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"> <div class="wp-block-embed__wrapper"> <div class="ast-oembed-container"><iframe title="How to Print a List of List in Python?" width="1400" height="788" src="https://www.youtube.com/embed/F1gddgWWaEI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div> </div> </figure> <p>As an exercise, you can also try it yourself in our interactive shell:</p> <p> <iframe src="https://brython.info/console.html" width="800" height="400"></iframe> </p> <h2>Step-By-Step Problem Formulation</h2> <p>Do you want to print a <a href="https://blog.finxter.com/python-list-of-lists/" target="_blank" rel="noreferrer noopener">list of lists</a> in Python so that the format doesn’t look like a total mess? In this <a href="https://blog.finxter.com/python-crash-course/" target="_blank" rel="noreferrer noopener">tutorial</a>, I’ll show you how to orderly <a href="https://blog.finxter.com/print-python-list/">print </a>a list of lists in Python—without using any external library.</p> <p>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:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = [['Alice', 'Data Scientist', 121000], ['Bob', 'Java Dev', 99000], ['Ann', 'Python Dev', 111000]] print(lst)</pre> <p>The output is not very nice:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[['Alice', 'Data Scientist', 121000], ['Bob', 'Java Dev', 99000], ['Ann', 'Python Dev', 111000]]</pre> <p>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:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[['Alice', 'Data Scientist', 121000], ['Bob', 'Java Dev', 99000], ['Ann', 'Python Dev', 111000]]</pre> <p>And maybe, you even want to see an output that aligns the three columns as well like this one:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Alice Data Scientist 121000 Bob Java Dev 99000 Ann Python Dev 111000 </pre> <p>I’ll show you all those different ways of printing a list of lists next. So let’s start with the easiest one:</p> <h2>Print List of Lists With Newline</h2> <p><strong>Problem</strong>: Given a list of lists, print it one row per line.</p> <p><strong>Example</strong>: Consider the following example list:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = [[1, 2, 3], [4, 5, 6]]</pre> <p>You want to print the list of lists with a newline character after each inner list:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1 2 3 4 5 6</pre> <p><strong>Solution</strong>: Use a for loop and a simple print statement:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = [[1, 2, 3], [4, 5, 6]] for x in lst: print(*x) </pre> <p>The output has the desired form:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1 2 3 4 5 6</pre> <p><strong>Explanation</strong>: The <a href="https://blog.finxter.com/what-is-asterisk-in-python/" target="_blank" rel="noreferrer noopener">asterisk operator</a> “unpacks” all values in the inner list <code>x</code> into the print statement. You must know that the print statement also takes multiple inputs and prints them, whitespace-separated, to the shell.</p> <p><strong>Related articles</strong>:</p> <ul> <li><a rel="noreferrer noopener" href="https://blog.finxter.com/what-is-asterisk-in-python/" target="_blank">Unpacking Operator *</a></li> <li><a rel="noreferrer noopener" href="https://blog.finxter.com/print-python-list/" target="_blank">How to Print a List Beautifully</a></li> <li><a href="https://blog.finxter.com/python-list-of-lists/" target="_blank" rel="noreferrer noopener">Python Lists of Lists</a></li> </ul> <h2>Print List of Lists Without Brackets</h2> <p>To print a list of lists without brackets, use the following code again.</p> <p><strong>Solution</strong>: Use a for loop and a simple print statement:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = [[1, 2, 3], [4, 5, 6]] for x in lst: print(*x) </pre> <p>The output has the desired form:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1 2 3 4 5 6</pre> <p>But how can you print a list of lists by aligning the columns?</p> <h2>Print List of Lists Align Columns</h2> <p><strong>Problem</strong>: How to print a list of lists so that the columns are aligned?</p> <p><strong>Example</strong>: Say, you’re going to print the list of lists. </p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[['Alice', 'Data Scientist', 121000], ['Bob', 'Java Dev', 99000], ['Ann', 'Python Dev', 111000]]</pre> <p>How to align the columns?</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Alice 'Data Scientist', 121000], Bob 'Java Dev', 99000], Ann 'Python Dev', 111000]]</pre> <p><strong>Solution</strong>: 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). </p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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))</pre> <p>The output is the desired:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Alice Data Scientist 121000 Bob Java Dev 99000 Ann Python Dev 111000 </pre> <p><strong>Explanation:</strong> </p> <ul> <li>First, you determine the length <code>n</code> (in characters) of the largest string in the list of lists using the statement <code>max(len(x) for l in lst for x in l)</code>. The code uses a <a rel="noreferrer noopener" href="https://blog.finxter.com/how-does-nested-list-comprehension-work-in-python/" target="_blank">nested for loop in a generator expression</a> to achieve this.</li> <li>Second, you iterate over each list in the list of lists (called <code>row</code>). </li> <li>Third, you create a string representation with columns aligned by ‘padding’ each row element so that it occupies <code>n+2</code> characters of space. The missing characters are filled with empty spaces.</li> </ul> <p>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:</p> <p> <iframe width="800" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code=%23%20Create%20the%20list%20of%20lists%0Alst%20%3D%20%5B%5B'Alice',%20'Data%20Scientist',%20'121000'%5D,%0A%20%20%20%20%20%20%20%5B'Bob',%20'Java%20Dev',%20'99000'%5D,%0A%20%20%20%20%20%20%20%5B'Ann',%20'Python%20Dev',%20'111000'%5D%5D%0A%0A%0A%23%20Find%20maximal%20length%20of%20all%20elements%20in%20list%0An%20%3D%20max%28len%28x%29%20for%20l%20in%20lst%20for%20x%20in%20l%29%0A%0A%23%20Print%20the%20rows%0Afor%20row%20in%20lst%3A%0A%20%20%20%20print%28''.join%28x.ljust%28n%20%2B%202%29%20for%20x%20in%20row%29%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe> </p> <p><strong>Related articles</strong>: You may need to refresh your understanding of the following Python features used in the code:</p> <ul> <li><a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">List comprehension and generator expressions</a></li> <li><a rel="noreferrer noopener" href="https://blog.finxter.com/print-python-list/" target="_blank">String join()</a></li> <li><a rel="noreferrer noopener" href="https://blog.finxter.com/print-python-list/" target="_blank">Printing lists</a></li> </ul> <h2>Print List of Lists with Pandas</h2> <p>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:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""> lst = [['Alice', 'Data Scientist', '121000'], ['Bob', 'Java Dev', '99000'], ['Ann', 'Python Dev', '111000']] import pandas as pd df = pd.DataFrame(lst) print(df) </pre> <p>The output looks beautiful—like a spreadsheet in your Python shell:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""> 0 1 2 0 Alice Data Scientist 121000 1 Bob Java Dev 99000 2 Ann Python Dev 111000</pre> <h2>Where to Go From Here?</h2> <p>Enough theory, let’s get some practice!</p> <p>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?</p> <p><strong>Practice projects is how you sharpen your saw in coding!</strong></p> <p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p> <p>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.</p> <p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p> <p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p></p> </div> https://www.sickgaming.net/blog/2020/05/01/how-to-print-a-list-of-list-in-python/ |