0

Suppose a list: s = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]

I understand how to print every item in the list:

for i in s:
    print (i)

which gives:

A
B
C
D
E
F
G
H
I
J

But suppose I want to split the printing in terms of n. So if n = 3:

A
B
C

D
E
F

G
H
I

J

These are my attempts:

k = 0
for i in s:
    while k < n:
        k += 1
        print (i)

and

k = 0
while k < n:
    for i in s:
        print (i)
    k += 1

I understand that my attempts are way off, but I can't seem to get it. I know you can create sub-lists in terms of n and solve it that way, but is there a way you can do this otherwise?

2 Answers 2

1
k = 0
for i in s:
    if k == n-1:
       print i + '\n'
       k = 0
    else:
        print i
        k += 1
Sign up to request clarification or add additional context in comments.

Comments

0
>>> s = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
>>> n=3
>>> print('\n\n'.join(['\n'.join(s[i:i+n]) for i in range(0,len(s),n)]))
A
B
C

D
E
F

G
H
I

J

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.