l1 = [1,2,3,4,5]
l2 = ["a","b","c"]
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.
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')]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With