pythonlistpython-3.4

How to print two lists of different size side by side?


I have two lists of different length that I want to print side by side, separated by a tab. As an example:

a_list = ["a","b","c","d","e"]
b_list = ["f","g","h","i","j","k","l","m","n"]

I tried:

print('A-list:'+ '\t' + 'B-list:')
for i in range(len(b_list)):
    print(a_list[i] + '\t' + b_list[i])

I off course get an "out of range-trace" back because one list is shorter. I do not wish to use zip.


Solution

  • This is a possible solution. It doesn't matter if a_list is longer or shorter than b_list.

    def get(lst, idx):
        try:
            return lst[idx]
        except:
            return " "
    
    a_list = ['a','b','c','d','e'] 
    b_list = ['f','g','h','i','j','k','l','m','n']
    
    result = []
    
    for i in range(min(len(a_list), len(b_list))):
        result.append(get(a_list, i))
        result.append(get(b_list, i))
    
    for i in range(min(len(a_list), len(b_list)), max(len(a_list), len(b_list))):
        result.append(get(a_list, i))
        result.append(get(b_list, i))
    
    print('\n'.join('\t'.join((result[i], result[i+1]))
                              for i in range(0, len(result), 2)))
    

    This prints the expected output:

    a   f
    b   g
    c   h
    d   i
    e   j
        k
        l
        m
        n