Search code examples
pythonpython-3.xlistpython-itertools

Python list iteration exhaustion


How do i iterate over two lists simultaneously, One list is bigger than the second one. So the second one exhausts. I want to start the smaller list again till the bigger one exhausts

_list = [ 19 , 74, 544, 39, 00, 34, 44, 593, 33, 2123, 22]
_list1 = [0, 1, 2, 3, 4]

Things i have tried:

I used itertools.zip_longest but i don't know what to use in fillvalue.

Needed Output:

The output i desire : (19, 0), (74, 1) ----- (34, 5) (44, 0) (593, 1) until the bigger list exhausts.


Solution

  • One list is bigger than the second one. So the second one exhausts. I want to start the smaller list again till the bigger one exhausts

    You might combine itertools.cycle and zip following way

    import itertools
    li1 = [19, 74, 544, 39, 00, 34, 44, 593, 33, 2123, 22]
    li2 = [0, 1, 2, 3, 4]
    for i in zip(li1, itertools.cycle(li2)):
        print(i)
    

    output

    (19, 0)
    (74, 1)
    (544, 2)
    (39, 3)
    (0, 4)
    (34, 0)
    (44, 1)
    (593, 2)
    (33, 3)
    (2123, 4)
    (22, 0)