zip list with different length

Peter Otten __peter__ at web.de
Wed Apr 4 04:42:34 EDT 2007


s99999999s2003 at yahoo.com wrote:

> suppose i have 2 lists, a, b then have different number of elements,
> say len(a) = 5, len(b) = 3
>>>> a = range(5)
>>>> b = range(3)
>>>> zip(b,a)
> [(0, 0), (1, 1), (2, 2)]
>>>> zip(a,b)
> [(0, 0), (1, 1), (2, 2)]
> 
> I want the results to be
> [(0, 0), (1, 1), (2, 2) , (3) , (4) ]
> can it be done?
> thanks

from itertools import izip, chain, repeat, takewhile, starmap

def zip_longest(*seqs):
    padded = [chain(izip(s), repeat(())) for s in seqs]
    return takewhile(bool, starmap(sum, izip(izip(*padded), repeat(()))))

Just to bring itertools to your attention :-)

Peter



More information about the Python-list mailing list