Reputation: 169
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
Upvotes: 1
Views: 2757
Reputation: 13697
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
Upvotes: 1
Reputation: 9170
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)
Upvotes: 1
Reputation: 32189
You can do that as follows:
for i,item in enumerate(listA):
if (i+1)%4 == 0:
print(item)
else:
print(item,end=' ')
Upvotes: 3