Best pattern/idiom

Duncan Booth duncan.booth at invalid.invalid
Tue Aug 10 09:18:05 EDT 2004


Heiko Wundram <heikowu at ceosg.de> wrote in
news:mailman.1442.1092142146.5135.python-list at python.org: 

> Problem being:
> 
>>>> list(chop([1,2,3,4,5,6],4))
> [(1, 2, 3, 4)]
> 
> If you actually want to get back everything from iterator, better do
> something like:
> 
> def ichop(it,n,rtype=list):
>     it = iter(it)
>     empty = False
>     while not empty:
>         retv = []
>         while not empty and len(retv) < n:
>             try:
>                 retv.append(it.next())
>             except StopIteration:
>                 empty = True
>         if retv:
>             yield rtype(retv)

It depends what you actually want to get if the list isn't a multiple of n. 
The uneven length tuple at the end seems a bit bad, you are probably better 
off with something like this:

>>> def chop(it, n):
	tup = (itertools.chain(iter(it), (None,)*(n-1)),)*n
	return itertools.izip(*tup)

>>> list(chop([1,2,3,4,5,6],4))
[(1, 2, 3, 4), (5, 6, None, None)]

although this still loses your data if n < 1.



More information about the Python-list mailing list