Search code examples
pythonlistloopsformattabular

Printing a list in tabular format using loop


Looking how to get my list such as,

myList = ["1", "2", "3", "4", "5", "6", "8", "9"]

into a tabular format like,

1    2    3
4    5    6
7    8    9

I would prefer using a loop to automate it so that it picks the first 3 items from the list and then moves the next 3 onto the next row and so on. I found similar problems but couldn't find out how to implement it into my program, I am just a beginner in python.

Thanks!


Solution

  • myList = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    

    Below, we enumerate myList, and we print a newline every 3 characters.

    for j, i in enumerate(myList):
        if j%3==0:
            print('\n')
        print(i, end= " ")
    

    Output:

    1 2 3 
    
    4 5 6 
    
    7 8 9