Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

join two lists which don't have same length, repeating shortest

Tags:

python

list

I have two lists:

l1 = [1,2,3,4,5]
l2 = ["a","b","c"]

My expected output:

l3 = [(1,"a"),(2,"b"),(3,"c"),(4,"a"),(5,"b")]

So basically I'm looking to join two lists and when they are not same lenght i have to spread items from other list by repeating from start.

I tried:

using zip() but it is bad for this case as it join with equal length

>>> list(zip(l1,l2))
[(1, 'a'), (2, 'b'), (3, 'c')]
like image 282
vdkd Avatar asked Mar 02 '23 20:03

vdkd


1 Answers

You can use itertools.cycle so that zip aggregates elements both from l1 and a cycling version of l2:

from itertools import cycle

list(zip(l1, cycle(l2)))
# [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'a'), (5, 'b')]

cycle is very useful when the iterable over which you are cycling is combined or zipped with other iterables, so the iterating process will stop as soon as some other iterable is exhausted. Otherwise it will keep cycling indefinitely (in the case there is a single cycle generator or also that all other iterables are also infinite as @chepner points out)

like image 189
yatu Avatar answered Mar 05 '23 17:03

yatu