Skip to content

Instantly share code, notes, and snippets.

@durden
Created September 10, 2011 15:37
Show Gist options
  • Save durden/1208443 to your computer and use it in GitHub Desktop.
Save durden/1208443 to your computer and use it in GitHub Desktop.
Iterate of a list chunk by chunk
class ListChunk:
def __init__(self, items, chunksize):
self.items = items
self.chunksize = chunksize
self.ii = 0
def __iter__(self):
return self
def next(self):
if self.ii >= len(self.items):
raise StopIteration
tmp = self.items[self.ii:self.ii + self.chunksize]
self.ii = self.ii + self.chunksize
return tmp
items = ListChunk([1,2,3,4,5,5,6,7,8], 2)
for slice in items:
print slice
@kennethreitz
Copy link

Really the easiest thing to do is just write a generator:

def chunk(l, chunksize):
    for i in range(0, len(l), chunksize):
        yield l[i:i+chunksize]
>>> items = chunk([1,2,3,4,5,5,6,7,8], 2)
>>> for item in items:
...    print item

[1, 2]
[3, 4]
[5, 5]
[6, 7]
[8]

@durden
Copy link
Author

durden commented Sep 10, 2011

Nice, the generator solution is way better!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment