[Tutor] Iterate Suggestion

Peter Otten __peter__ at web.de
Mon Apr 16 08:55:29 CEST 2012


Tom Tucker wrote:

> Hello all.  Any suggestions how I could easily iterate over a list and
> print the output 3 across (when possible)?  One method I was considering
> was removing the recently printed item from the list, checking list
> length,
> etc.  Based on the remaining length of the list I would then print X
> across. Yah? Is their and easier approach I might be overlooking?
> 
> 
> For example...
> 
> mylist = ['serverA', 'serverB', 'serverC', 'serverD',' serverE',
> 'serverF', 'serverG']
> 
> 
> Desired Output
> ============
> serverA  serverB  serverC
> serverD  serverE  serverF
> serverG

Here's another approach that works with arbitrary iterables, not just lists:

>>> from itertools import islice
>>> def chunks(items, n, rowtype=tuple):
...     items = iter(items)
...     while True:
...             row = rowtype(islice(items, n))
...             if not row: break
...             yield row
... 
>>> for row in chunks(range(7), 3):
...     print row
... 
(0, 1, 2)
(3, 4, 5)
(6,)
>>> mylist = ["server" + c for c in "ABCDEFG"]
>>> for row in chunks(mylist, 3, " ".join):
...     print row
... 
serverA serverB serverC
serverD serverE serverF
serverG




More information about the Tutor mailing list