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

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.


Try

result = ["_".join((i, j)) for i, j in itertools.izip(la, itertools.cycle(lb))]

import itertools
la = ['a1', 'a2', 'a3', 'a4']
lb = ['b1', 'b2']
for i, j in zip(la, itertools.cycle(lb)):
    print('_'.join((i,j)))

Tags:

Python

Loops

List