1

Given a list of strings I want to be able to print 4 items of that list per line with one space between them until the list is exhausted. Any ideas? Thanks

Example:

ListA = ['1', '2', '3', '4', '5', '6']

Given this list I would like my output to be:

1 2 3 4
5 6
sshashank124
  • 31,495
  • 9
  • 67
  • 76
carcinogenic
  • 169
  • 1
  • 2
  • 10

3 Answers3

3

You can do that as follows:

for i,item in enumerate(listA):
    if (i+1)%4 == 0:
        print(item)
    else:
        print(item,end=' ')
sshashank124
  • 31,495
  • 9
  • 67
  • 76
1

Another approach is something like this:

ListA = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13']

k = 0
group = ''

for i in ListA:
    if k < 4:
        group += i + ' '
        k += 1
    else:
        group += '\n' + i + ' '
        k = 1

print(group)
wigging
  • 8,492
  • 12
  • 75
  • 117
1

Alternatively, one can split the given list to chunks beforehand. See How do you split a list into evenly sized chunks? for various approaches:

my_list = ['1', '2', '3', '4', '5', '6']
n = 4
chunks = (my_list[i:i+n] for i in range(0, len(my_list), n))
for chunk in chunks:
    print(*chunk)
# 1 2 3 4
# 5 6
Georgy
  • 12,464
  • 7
  • 65
  • 73