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

Viewed 674

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.

6 Answers

your code is rasing IndexError because the length of b_list is greater than the length of a_list, for this, you could use a try except statement:

for i in range(max(len(b_list), len(a_list))):
    try:
        print(f"{a_list[i]}\t", end="")
    except IndexError:
        print(f" \t", end="")
    try:
        print(f"{b_list[i]}\t")
    except IndexError:
        print(f" \t")

output:

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

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

without any extra loop:

list_a = ["A", "B", "C"]
list_b = ["1", "2", "3", "4"]
len_a = len(list_a)
len_b = len(list_b)
i = 0
while True:
    if i < len_a:
        print(list_a[i], end="")
    if i < len_b:
        print("\t", list_b[i], end="")
    print()
    i += 1
    if i > max(len_a, len_a):
        break
def iterate(a_list, b_list):
  # iterate through short list
  min_length = min(((len(a_list), len(b_list)))) 

  for i in range(min_length):
    print('{}\t{}'.format(a_list[i], b_list[i]))

  # print remaining items accordingly
  if i + 1 == len(a_list):
    for item in b_list[i+1:]:
      print('\t{}'.format(item))  
  else:
    for item in a_list[i+1:]:
      print(item) 

I advise use the string method format which allows you to have elements of any kind in your lists.

In all solutions, the trick is to go through the longest list and use an empty space for missing entries in the shorter list.

For example:

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

for i in range(max(len(a_list),len(b_list))):
    a = a_list[i:i+1] or [""]
    b = b_list[i:i+1] or [""]
    print(a[0]+"\t"+b[0])

If you're not concerned with memory usage, you could also pad the lists with blanks in order to have a simpler printing process that assumes lists of same sizes:

padding  = len(b_list)-len(a_list)
a_padded = a_list + [""]*padding
b_padded = b_list + [""]*-padding
for i in range(len(a_padded)):
    print(a_padded[i]+"\t"+b_padded[i])

You could try this:

test1 = [1, 2, 3, 4]
test2 = [1, 2, 3, 4, 5]
test3 = [1, 2]

while test or test2 or test3:
    print(test.pop() if test else '',\
          test2.pop() if test2 else '',\
          test3.pop()if test3 else '')
Related