1

For example, I want to zip two different sized list:

list1=[1,2,3]
list2=[1,2,3,4]

# zip the two list will be [(1,1),(2,2),(3,3)]
zip(list1, list2)

What I want is:

[(1,1),(2,2),(3,3),(None,4)]

Is there any simple way to achieve this?

Miedena
  • 123
  • 1
  • 12
  • 3
    Does this answer your question? [Is there a zip-like function that pads to longest length in Python?](https://stackoverflow.com/questions/1277278/is-there-a-zip-like-function-that-pads-to-longest-length-in-python) – Phu Ngo May 28 '20 at 04:09

3 Answers3

3

There is zip_longest in itertools which does that:

>>> from itertools import zip_longest
>>> list(zip_longest(range(1,4), range(1,5)))
[(1, 1), (2, 2), (3, 3), (None, 4)] 
A. Maman
  • 853
  • 1
  • 7
  • 18
Aivar Paalberg
  • 4,645
  • 4
  • 16
  • 17
2

i think you want itertools.zip_longest

>>> list1=[1,2,3]
>>> list2=[1,2,3,4]
>>> import itertools
>>> list(itertools.zip_longest(list1, list2))
[(1, 1), (2, 2), (3, 3), (None, 4)]

Dave Ankin
  • 1,060
  • 2
  • 9
  • 20
0

This:

list1=[1,2,3]
list2=[1,2,3,4]

for _ in range(len(list2)-len(list1)): list1.append(None)

print(list(zip(list1, list2)))

Output:

[(1, 1), (2, 2), (3, 3), (None, 4)]
Red
  • 26,798
  • 7
  • 36
  • 58