Help With Python For Loops

Is there a way to continue looping through the rest of the strings once var2 is done? Business and Entertainment get cut off

# var1 = Business
# var2 = Food
# var3 = Entertainment
  for x, y, z in zip(var1, var2, var3):
    chartString += '     ' + x  + '  ' + y + '  ' + z + '\n'
     B  F  E
     u  o  n
     s  o  t
     i  d  e

Cheers :+1:

You could do a check to see which word has the longest length and continue printing out until that point. If a word finishes beforehand, print out an empty string for each round.

Something like:

def findLongestString():
  return lengthOfLongestString

for element in lengthOfLongestString:
  for x, y, z in zip(var1, var2, var3):
    # if x, y, or z === "" (or whatever they come out to be, null) then continue
        chartString += '     ' + x  + '  ' + y + '  ' + z + '\n'
1 Like

I went ahead and found the max variable length and added the correct amount of spaces until it matched the max length. That seemed to do the trick :wink:

Thank you singhshemona

  maxLength = max(len(categoryList[0]), len(categoryList[1]), len(categoryList[2]))
  newList = []

  for x in categoryList:
    if len(x) < maxLength:
      newList.append(x + ' ' * (maxLength - len(x)))

  var1, var2, var3 = newList

  for x, y, z in zip(var1, var2, var3):
    chartString += '     ' + x  + '  ' + y + '  ' + z + '\n'
1 Like

Just count the big word

From the zip docs:

zip() should only be used with unequal length inputs when you donโ€™t care about trailing, unmatched values from the longer iterables. If those values are important, use itertools.zip_longest() instead.

zip_longest should do exactly what you are looking for without manually manipulating the input values :slight_smile:

1 Like