Skip to content
Advertisement

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

I have a list of unknown number of items, let’s say 26. let’s say

list=['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']

How to print like this:

abcde

fghij

klmno

pqrst

uvwxy

z

? Thank you very much. Attempt:

    start = 0
    for item in list:
        if start < 5:
            thefile.write("%s" % item)
            start = start + 5
        else:
            thefile.write("%s" % item)
            start = 0

Advertisement

Answer

It needs to invoke for-loop and join functions can solve it.

l=['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']

for i in range(len(l)/5+1):
    print "".join(l[i*5:(i+1)*5]) + "n"

Demo:

abcde

fghij

klmno

pqrst

uvwxy

z
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement