0

I have two lists:

list1=[1,2,3]
list2=[4,5,6,7]

And I want to iterate over them. What I want to obtain is something similar to this:

1,4
2,5
3,6
 ,7

I have thought of using the zip function but it doesn't seem to work with different length lists as by using the following code:

for l1, l2 in list1, list2:
     print(l1,l2)

I get this:

1,4
2,5
3,6

So the number 7 is missing. I wonder how could I adapt the code or if there is any other option I am missing to iterate in parallel when the lists are of different lengths?

marisa
  • 29
  • 2
  • 8

3 Answers3

5

I think you need zip_longest:

from itertools import zip_longest
list1=[1,2,3]
list2=[4,5,6,7]
for l1, l2 in zip_longest(list1, list2):
     print(l1,l2)
# 1 4
# 2 5                                                        
# 3 6                                                         
# None 7                                                      

Even more specific to your question, use fillvalue with zip_longest:

from itertools import zip_longest
list1=[1,2,3]
list2=[4,5,6,7]
for l1, l2 in zip_longest(list1, list2, fillvalue=' '):
     print(l1,l2)
# 1 4
# 2 5                                                         
# 3 6                                                         
#   7                                                        
Austin
  • 25,759
  • 4
  • 25
  • 48
1

You need zip_longest:

>>> from itertools import zip_longest
>>> a = [1,2,3]
>>> b = [4,5,6,7]
>>> list(zip_longest(a, b))
[(1, 4), (2, 5), (3, 6), (None, 7)]
kiyah
  • 1,502
  • 2
  • 18
  • 27
0

Check zip_longest() from itertools (a very useful module in Python Standard Library)

from itertools import zip_longest
for l1, l2 in zip_longest(list1, list2, fillvalue=''):
     print(l1,l2)
D_Serg
  • 464
  • 2
  • 12