The Python Oracle

Is there a zip-like function that pads to longest length?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Meadow

--

Chapters
00:00 Question
00:29 Accepted answer (Score 365)
01:20 Answer 2 (Score 92)
01:43 Answer 3 (Score 8)
02:50 Answer 4 (Score 7)
03:08 Thank you

--

Full question
https://stackoverflow.com/questions/1277...

Question links:
[zip()]: https://docs.python.org/3/library/functi...

Accepted answer links:
[itertools.zip_longest]: https://docs.python.org/3/library/iterto...
[itertools.izip_longest]: https://docs.python.org/2/library/iterto...
[feature of ]: https://docs.python.org/2/library/functi...

Answer 2 links:
[izip_longest]: http://docs.python.org/library/itertools...
[zip_longest]: https://docs.python.org/3/library/iterto...

Answer 3 links:
[zip()]: https://docs.python.org/3/library/functi...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #zip

#avk47



ACCEPTED ANSWER

Score 399


In Python 3 you can use itertools.zip_longest

>>> list(itertools.zip_longest(a, b, c))
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

You can pad with a different value than None by using the fillvalue parameter:

>>> list(itertools.zip_longest(a, b, c, fillvalue='foo'))
[('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')]

With Python 2 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)]



ANSWER 2

Score 92


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)]



ANSWER 3

Score 9


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)



ANSWER 4

Score 4


non itertools My Python 2 solution:

if len(list1) < len(list2):
    list1.extend([None] * (len(list2) - len(list1)))
else:
    list2.extend([None] * (len(list1) - len(list2)))