Print a list of lists in separate lines in Python

In this article, we will discuss different ways to print each sublist in a list of lists in separate line in Python.

Table Of Contents

Introduction

Suppose we have a list of lists in Python like this,

listOfLists = [ [11, 12, 13, 14, 15, 16],
                [21, 22, 23, 24, 25, 26],
                [31, 32, 33, 34, 35, 36] ]

And we want to print each sublist in a separate line,

11 12 13 14 15 16
21 22 23 24 25 26
31 32 33 34 35 36

There are different ways to do this, and we will discuss them one by one in this article.

Method 1: Using for loop

The first way is to iterate over the list of lists, and for each sublist print it on the console. This way each sublist will be printed in a separate line. So lets see an example where we will use the for loop to achieve the result.

listOfLists = [ [11, 12, 13, 14, 15, 16],
                [21, 22, 23, 24, 25, 26],
                [31, 32, 33, 34, 35, 36] ]

for subList in listOfLists:
    print(*subList)

Output:

11 12 13 14 15 16
21 22 23 24 25 26
31 32 33 34 35 36

Method 2: By converting into string

The second way is an interesting way, in which we will convert our list of lists to a string. Where each sublist will be separated by a new line character. This way, in this new string object we will have multiple lines, and each line will contain a sublist from the original list. Then we can print this string on the console. So basically in this approach, we will print each each sublist of the list on the console in a separate line. Let’s see the example,

listOfLists = [ [11, 12, 13, 14, 15, 16],
                [21, 22, 23, 24, 25, 26],
                [31, 32, 33, 34, 35, 36] ]

strValue= '\n'.join(' '.join(str(elem) \
                    for elem in sublist) \
                    for sublist in listOfLists)

print(strValue)

Output:

11 12 13 14 15 16
21 22 23 24 25 26
31 32 33 34 35 36

Summary

We learned about two different ways to print each sublist in a list of lists in a separate line in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top