1

So I have a list:

names = ['dog','cat','mouse','moose','rabbit','horse','apple','banana','orange']

I want the output to be like this:

dog cat mouse moose rabbit horse
apple banana orange

So basically a max of six words per line displayed when printed.

I'm honestly clueless where to start, because a for loop as such will display 1 per line:

for i in names:
   print(i)

output -->
dog
cat
mouse
moose
rabbit
horse
apple
banana
orange
ajkey94
  • 411
  • 2
  • 10
  • 19
  • check this http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python – avasal Apr 10 '13 at 05:36

3 Answers3

3

You could use range with a step to split it up:

names = ['dog','cat','mouse','moose','rabbit','horse','apple','banana','orange']

for i in range(0, len(names), 6):
    print(names[i:i + 6])
Blender
  • 289,723
  • 53
  • 439
  • 496
0

Poor man's version:

counter = 0
for i in names:
    if counter == 5:
        counter = 0
        print i
    else:
        print i,
    counter += 1
eazar001
  • 1,572
  • 2
  • 16
  • 29
0

Using textwrap with a maximum 35 characters line width, which helps if you have words of varying sizes:

import textwrap
names = ['dog','cat','mouse','moose','rabbit','horse','apple','banana','orange']
for l in textwrap.wrap("\n".join(names),35):
    print l

This is useful if you want to right justify your output. I think splitting on the number of words is useful if you want to generate white-space delimited columns.

perreal
  • 94,503
  • 21
  • 155
  • 181