Is there a built-in function that works like zip() but that will pad the results so that the length of the resultant list is the length of the longest input rather than the shortest input?

>>> a=['a1']
>>> b=['b1','b2','b3']
>>> c=['c1','c2']

>>> zip(a,b,c)
[('a1', 'b1', 'c1')]

>>> What command goes here?
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
share|improve this question
up vote 115 down vote accepted

You can either use itertools.izip_longest (Python 2.6+), or you can use map with None. It is a little known feature of map (but map changed in Python 3.x, so this only works in Python 2.x).

>>> map(None, a, b, c)
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
share|improve this answer
1  
@SilentGhost, I took your word that this doesn't work in py3k. I don't have py3k to confirm. – Nadia Alramli Aug 14 '09 at 11:35
1  
>>> list(map(None, a, b, c)) Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> list(map(None, a, b, c)) TypeError: 'NoneType' object is not callable – SilentGhost Aug 14 '09 at 11:36
    
you can also consult the docs: docs.python.org/3.1/library/functions.html#map – SilentGhost Aug 14 '09 at 11:37
2  
Do we not have a non itertools Python 3 solution? – PascalvKooten Mar 24 '15 at 12:51

For Python 2.6x use itertools module's izip_longest.

For Python 3 use zip_longest instead (no leading i).

>>> list(itertools.izip_longest(a, b, c))
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
share|improve this answer
5  
In case you want to make your code both python 2 and python 3 compatible, you can use six.moves.zip_longest instead. – Gamrix Apr 14 '16 at 19:51

non itertools Python 3 solution:

def zip_longest(*lists):
    def g(l):
        for item in l:
            yield item
        while True:
            yield None
    gens = [g(l) for l in lists]    
    for _ in range(max(map(len, lists))):
        yield tuple(next(g) for g in gens)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.