Over a million developers have joined DZone.

Iterator To Return N Items At-a-time

·
Copied from paul cannon's recipe here

def group(iterator, count):
    itr = iter(iterator)
    while True:
        yield tuple([itr.next() for i in range(count)])

After the above definition, you can use it very easily.

>>> list(group([0, 1, 2, 3, 4, 5], 2))
[(0, 1), (2, 3), (4, 5)]

>>> dataset = ['Nausori', 5, 'Namadi', 10, 'Suva', 3]
>>> for place, value in group(dataset, 2):
...   print '%s: %s' % (place, value)
... 
Nausori: 5
Namadi: 10
Suva: 3

The above code is somewhat simplified. 
See the recipe for full discussion.
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}