1

I have a list of lists in python, each of the list within the list have the same number of elements.

sample_list = [['1','22222222222222222','333'],
               ['111111111','2','3'],
               ['1','2','3']]

I want to print out the elements in the list so that they look like this.

1          22222222222222222  333 
111111111  2                  3
1          2                  3

In between the longest item to the next column there will be 2 spaces. So in the 2nd row first column the series of 1s continue and another 2 spaces later is when the next column continues. I won't know the exact length of each element so just using tabs(\t) won't work. How can I print the nested list into a table of columns separated by 2 spaces?

Edit : I want to as much as possible avoid external modules and I need it to be in python 2

eclipse
  • 197
  • 1
  • 5
  • 16

1 Answers1

3

Something like this:

sample_list = [['1','22222222222222222','333'],
               ['111111111','2','3'],
               ['1','2','3']]

Alternative 1:

# Store max lengths
l = [len(max(i, key=len)) for i in zip(*sample_list)]

for item in sample_list:
    for idx in range(len(l)):
        print(item[idx].ljust(l[idx]), end='  ')
    print()

Alternative 2 (less readable but no artifacts)

# Store max lengths
l = [len(max(i, key=len)) for i in zip(*sample_list)]

print('\n'.join('  '.join(item[i].ljust(l[i]) for i in range(len(l))) 
              for item in sample_list))

Alternative 1 (python2):

# Store max lengths
l = [len(max(i, key=len)) for i in zip(*sample_list)]

for item in sample_list:
    for idx in range(len(l)):
        print item[idx].ljust(l[idx]), "",
    print

1          22222222222222222  333  
111111111  2                  3    
1          2                  3    
Anton vBR
  • 18,287
  • 5
  • 40
  • 46