31

I am sure there is an easy and obvious way to do this, but I have been googling and reading the docs and I just cannot find anything.

This is what I want to achieve:

la = ['a1', 'a2', 'a3', 'a4']
lb = ['b1', 'b2']
result = ['a1_b1', 'a2_b2', 'a3_b1', 'a4_b2']

I have a list of dates and some of them have something marked on them. I then have a much larger list of dates and I want to put the smallest list inside the bigger list as many times as possible. It will probably require some sort of loop as I need access to the dates in the larger list for the end result.

For some reason, I just cannot see a good way to do this.

Georgy
  • 9,972
  • 7
  • 57
  • 66
Mathias Nielsen
  • 1,490
  • 1
  • 17
  • 29
  • Does this answer your question? [How to zip two differently sized lists?](https://stackoverflow.com/questions/19686533/how-to-zip-two-differently-sized-lists) – Georgy Oct 17 '20 at 10:00
  • Does this answer your question? [Permutations between two lists of unequal length](https://stackoverflow.com/questions/12935194/permutations-between-two-lists-of-unequal-length) – Luis Sieira Dec 09 '21 at 09:12

3 Answers3

35

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.

snakile
  • 50,186
  • 60
  • 164
  • 235
20

Try

result = ["_".join((i, j)) for i, j in itertools.izip(la, itertools.cycle(lb))]
Sven Marnach
  • 530,615
  • 113
  • 910
  • 808
  • 3
    [izip is replaced with built-in zip in Python 3](https://stackoverflow.com/questions/32659552/izip-not-working-in-python-3-x) – Doopy Sep 15 '18 at 08:52
  • 5
    What to do if we don't know before which of `la` or `lb` will be exhausted first? – Moberg Aug 14 '19 at 08:00
1
import itertools
la = ['a1', 'a2', 'a3', 'a4']
lb = ['b1', 'b2']
for i, j in zip(la, itertools.cycle(lb)):
    print('_'.join((i,j)))
wwii
  • 21,286
  • 7
  • 34
  • 74