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)]
non itertools My Python 2 solution:
For Python 2.6x use
itertools
module'sizip_longest
.For Python 3 use
zip_longest
instead (no leadingi
).non itertools Python 3 solution:
In Python 3 you can use
itertools.zip_longest
You can pad with a different value than
None
by using thefillvalue
parameter:With Python 2 you can either use
itertools.izip_longest
(Python 2.6+), or you can usemap
withNone
. It is a little known feature ofmap
(butmap
changed in Python 3.x, so this only works in Python 2.x).