Search code examples
python

How to print list with numbers into nth columns or any tabulated format


I wanted to display a list into nth columns and add numbering in every item. So far, the code I have below has the numbering but the output is not divided into 2 columns as I wanted.

myList = ["AASD", "ASDASD", "QWEQ", "GFHG", "YUIYU", "NSDF", "LDFS", "QSDAD", "FDRT", "YSLSJ"]

count = 0
for j, i in enumerate(myList):
    count += 1
    if j%2==0:
        print('\n')
    #print(i, end= " ")             # using this, it will be in 2 columns but no numbers
    print ("{} {}".format(count,i)) # using this, with numbers but single column

Current Output:

1 AASD
2 ASDASD

3 QWEQ
4 GFHG

5 YUIYU
6 NSDF

7 LDFS
8 QSDAD

9 FDRT
10 YSLSJ

Needed Output:

1. AASD     2. ASDASD 
3. QWEQ     4. GFHG 
5. YUIYU    6. NSDF 
7. LDFS     8. QSDAD 
9. FDRT     10. YSLSJ 

Solution

  • for i, item in enumerate(myList, 1):
        print("{:2}. {:<10}".format(i, item), end="")
        if i % 2 == 0:
            print()  # new line
    

    Result:

     1. AASD       2. ASDASD    
     3. QWEQ       4. GFHG      
     5. YUIYU      6. NSDF      
     7. LDFS       8. QSDAD     
     9. FDRT      10. YSLSJ