tags:

views:

357

answers:

2

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)]
+6  A: 

itertools.izip_longest (note: it was renamed in py3k to zip_longest).

>>> list(itertools.izip_longest(a, b, c))
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
SilentGhost
You should mention this only works on python 2.6
Nadia Alramli
I've provided a link that **clearly states** that it was introduced in 2.6. 2.6 is a current stable version of python. If OP has a need for legacy version code it needs to be stated in question explicitly.
SilentGhost
2.5 is hardly legacy - it's just not the latest stable version
Draemon
that's the definition of legacy, dear.
SilentGhost
@SilentGhost, I take my note back. I'm unfortunate to be stuck with 2.5 for a long time. Thanks for the tests and notes.
Nadia Alramli
+11  A: 

You can either user itertools.izip_longest. But you need python 2.6 for that. Or you can use map with None. It is a little know feature of map but it doesn't work in py3k.

>>> map(None, a, b, c)
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
Nadia Alramli
You should mention this doesn't work in py3k.
SilentGhost
+ I didn't know map can do this :)
del-boy
@SilentGhost, fixed. Thanks for pointing this out.
Nadia Alramli
@SilentGhost, I took your word that this doesn't work in py3k. I don't have py3k to confirm.
Nadia Alramli
`>>> 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
you can also consult the docs: http://docs.python.org/3.1/library/functions.html#map
SilentGhost
@SilentGhost, thanks for the test!
Nadia Alramli