Hi people.
I am having trouble printing out a list of items with n items per line. Here is my current code.

def printList(lst, lineCount):
    # given a list of items, print it out in 
    # lineCount items per line.
    strList= '[ '
    for element in lst:
        strList = strList+ str(element) + ' '
        count= count +1
        if count%lineCount==0:
            strList = strList + '\n'

    strList=strList+ ' ]'
    return strList

Right now, the if statement is supposed to check if the list reaches the lineCount element in list. Then. I add the '\n' New line escape sequence to the list.

But right now the list is only printing the '\n' mark. What happened?

This is how I would do, maybe you can use it to debug your solution:

def list_str(lst, per_line):
    # given a list of items, 
    # return per_line items per line.
    start = '['
    while len(lst) > per_line:
        start += str(lst[:per_line])[1:-1]+','
        yield start
        start =''
        lst =lst[per_line:]
    yield start + str(lst[:per_line])[1:-1]+']'

def print_count(lst, count):
    print '\n'.join(list_str(lst, count))


Edited 6 Years Ago by pyTony: n/a

The code works fine for me on Slackware Linux. What are you using for input, and what output do you get?

This question has already been answered. Start a new discussion instead.