How to zip two differently sized lists?
You can use itertools.cycle
:
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely.
Example:
A = [1,2,3,4,5,6,7,8,9]
B = ["A","B","C"]
from itertools import cycle
zip_list = zip(A, cycle(B)) if len(A) > len(B) else zip(cycle(A), B)
Try this.
A = [1,2,3,4,5,6,7,8,9]
B = ["A","B","C"]
Z = []
for i, a in enumerate(A):
Z.append((a, B[i % len(B)]))
Just make sure that the larger list is in A
.
You can use itertools.cycle
:
from itertools import cycle
my_list = [1, 2, 3, 5, 5, 9]
another_list = ['Yes', 'No']
cyc = cycle(another_list)
print([[i, next(cyc)] for i in my_list])
# [[1, 'Yes'], [2, 'No'], [3, 'Yes'], [5, 'No'], [5, 'Yes'], [9, 'No']]