Skip to content

Instantly share code, notes, and snippets.

@squarepegsys
Created August 31, 2011 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save squarepegsys/1183831 to your computer and use it in GitHub Desktop.
Save squarepegsys/1183831 to your computer and use it in GitHub Desktop.
Get Python list in chunks
#!/usr/bin/env python
import unittest
## get a list in chunks
## if we run out of items in the list, start again from the beginning
class Chunker(object):
def __init__(self,flist,chunk_size):
self.current_pos=0
self.flist=flist
self.chunk_size=chunk_size
def next(self):
endpos = self.current_pos+self.chunk_size
sublist = self.flist[self.current_pos:endpos]
if len(sublist)<self.chunk_size:
items_short=self.chunk_size-len(sublist)
sublist+=self.flist[0:items_short]
self.current_pos=items_short
else:
self.current_pos=endpos
return sublist
class TestChunker(unittest.TestCase):
def test_get_list(self):
lst = range(10)
c = Chunker(lst,7)
self.assertEquals(range(7),c.next())
def test_get_rollover(self):
lst = range(10)
c = Chunker(lst,7)
self.assertEquals(range(7),c.next())
next = c.next()
self.assertEquals(7,len(next))
self.assertEquals([7,8,9,0,1,2,3],next)
self.assertEquals([4,5,6,7,8,9,0],c.next())
if __name__=='__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment