Search code examples
pythongenerator

How can I run two generators at same time in python


I want two generators yielding simultaneously, but any of them can be "hang" till the other one finishes.

def cal(tap):
        while (tap!=0):
            tap = tap-1
            yield tap

and I try to use the zip() to achieve but I got this as 7 and 5 for initial

     6 4
     5 3
     4 2
     3 1
     2 0

I want to achieve this:

     6 4
     5 3
     4 2
     3 1
     2 0
     1 0
     0 0

How can I do this? Do I need some support method or something?


Solution

  • Use itertools.zip_longest:

    from itertools import zip_longest
    
    g = zip_longest(cal(7), cal(5), fillvalue=0)
    
    list(g)
    

    Output:

    [(6, 4), (5, 3), (4, 2), (3, 1), (2, 0), (1, 0), (0, 0)]