Loop over 2 lists, repeating the shortest until end of longest [duplicate]

Assuming la is longer than lb:

>>> import itertools
>>> [x+'_'+y for x,y in zip(la, itertools.cycle(lb))]
['a1_b1', 'a2_b2', 'a3_b1', 'a4_b2']
  • itertools.cycle(lb) returns a cyclic iterator for the elements in lb.

  • zip(...) returns a list of tuples in which each element corresponds to an element in la coupled with the matching element in the iterator.

Leave a Comment