Print 5 items in a row on separate lines for a list?

You can simple do this by list comprehension: "\n".join(["".join(lst[i:i+5]) for i in xrange(0,len(lst),5)]) the xrange(start, end, interval) here would give a list of integers which are equally spaced at a distance of 5, then we slice the given list in to small chunks each with length of 5 by using list slicing.

Then the .join() method does what the name suggests, it joins the elements of the list by placing the given character and returns a string.

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

print "\n".join(["".join(lst[i:i+5]) for i in xrange(0,len(lst),5)])

>>> abcde
    fghij
    klmno
    pqrst
    uvwxy
    z

for i, a in enumerate(A):
    print a, 
    if i % 5 == 4: 
        print "\n"

Another alternative, the comma after the print means there is no newline character

Tags:

Python