Search code examples
python-3.xiterator

Empty cursor for iteration using zip


I have multiple cursors for iteration but when one of them is empty, the zip is not working. How can I iterate through other lists when one is empty. Sample code looks like below:

    for x, y, p, q in zip(cursor_X, cursor_Y,
                              cursor_P, cursor_Q):
    data1 = x
    data2 = y
    data3 = p
    data4 = q
print(str(data1['data']), end="")
print("\t" + str(data2['data']), end="")
print("\t" + str(data2['data']), end="")
print("\t" + str(data2['data']))

Solution

  • You can use itertools.zip_longest:

    itertools.zip_longest(*iterables, fillvalue=None)

    Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted

    You didn't show what your data looks like, but in order to make the rest of your code work, you could use a dict with a 'data' key and an empty string as value for missing data:

    from itertools import zip_longest
    
    for x, y, p, q in zip_longest(cursor_X, cursor_Y,
                                  cursor_P, cursor_Q,
                                  fillvalue={'data':''}):
        data1 = x
        data2 = y
        data3 = p
        data4 = q
    
        print(str(data1['data']), end="")
        print("\t" + str(data2['data']), end="")
        print("\t" + str(data2['data']), end="")
        print("\t" + str(data2['data']))
    

    Note that you could rewrite the content of the loop without unnecessary intermediate variables:

    for x, y, p, q in zip_longest(cursor_X, cursor_Y, cursor_P, cursor_Q,
                                  fillvalue={'data':''}):    
        out = '\t'.join(map(str, (x, y, z, t)))
        print(out)
    

    or even:

    for items in zip_longest(cursor_X, cursor_Y, cursor_P, cursor_Q,
                             fillvalue={'data':''}):    
        out = '\t'.join(map(str, items))
        print(out)