Python – Insert line break every x-number of elements

line-breakspython

I have looked around SO for similar questions, but it seems that this has only been asked for Visual Basic. What I want to do is rather simple, I guess, but being a beginner I can't seem to find the way to get it done.

I have a list of strings like this:

macrolist = ['hans', 'are', 'we', 'the', 'baddies', 'cake', 'or', 'death', 'cake', 'please', 'do', 'you', 'have', 'a', 'flag']

The problem is that this has been generated after reading from a tabbed file which has only 5 words per line, and then doing a number of changes in it (mainly shuffling). In order to generate an output file, I can join the elements of my list thus:

'\t'.join(macrolist)

…and then write it to a new file, but this will output a text file with just one line of tab-spaced items. I need to get a file which has only 5 words per line, like the original, so I thought that, before joining the list, I could insert a line break every 5 words. I've tried the following, but I get an error for "unsupported operand type(s) for /: 'str' and 'int'":

for index in macrolist:
    op = index/5
    if op is int:
        macrolist.append('\n')

print macrolist

The idea I had was that, if a given index was a multiple of 5, the code could insert a line break right afterwards. Then I could join the list and the output would be as desired. But, of course, even the design could be wrong… Any ideas?

Thanks in advance.

Best Solution

Try:

def chunks(l, n):
    """ Yield successive n-sized chunks from l.
    """
    for i in xrange(0, len(l), n):
        yield l[i:i+n]
chunks(macrolist,5)

Then iterate over the lists in the list like this:

for chunk in chunks(macrolist,5):
    print '\t'.join(chunk)  

The chunks code was taken form here. I would like to thank Ned Batchelder for that code.