6

If I have a list with:

["A","Bb","C","D","E","F","G"]

how can I iterate over it so that I can output the following:

"A Bb C"
"D E F"
"G"
Baz
  • 12,713
  • 38
  • 145
  • 268

3 Answers3

6

Get sublists of [0:3], [3:6], [6:9], ...

>>> xs = ["A","Bb","C","D","E","F","G"]
>>> [' '.join(xs[i:i+3]) for i in range(0, len(xs), 3)]
['A Bb C', 'D E F', 'G']
falsetru
  • 357,413
  • 63
  • 732
  • 636
6

Is a recipe that I keep hanging around.

def chunks(l, n):
    for i in xrange(0, len(l), n):
        yield l[i:i+n]
Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
3

You can use itertools.izip_longest here:

>>> from itertools import izip_longest
>>> L = ["A","Bb","C","D","E","F","G"]
>>> for item in izip_longest(*[iter(L)]*3, fillvalue=''):
...     print ' '.join(item)
... 
A Bb C
D E F
G  
TerryA
  • 58,805
  • 11
  • 114
  • 143