Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replicate a list to the length of list2?

I have list1 of a certain length and list2 of a certain length. Let's say:

list1 = [32, 345, 76, 54]

list2 = [43, 65, 76, 23, 12, 23, 44]

I need to make list1 loop back around until it is the same length as list2. Or, if list1 is longer, I need it to cut down to the length of list2. For the example above, I am looking to make:

list1 = [32, 345, 76, 54, 32, 345, 76]

It doesn't necessarily have to remain list1. It can be a new list I just need the same values from list1 looped back around a certain number of times. How do I go about doing this? I'm fairly new to python and I haven't been able to find anything that works.

like image 394
patels250 Avatar asked Nov 30 '25 04:11

patels250


2 Answers

Get to know the wonderful itertools module!

from itertools import cycle, islice

result = list(islice(cycle(list1), len(list2)))

If all you need is to iterate both list "together", this is even easier:

for x, y in zip(cycle(list1), list2):
    print(x, y)
like image 143
georg Avatar answered Dec 02 '25 18:12

georg


Use itertools.cycle:

from itertools import cycle

new_list1 = [element for element, index in zip(cycle(list1), range(len(list2)))]
new_list1

Output:

[32, 345, 76, 54, 32, 345, 76]
like image 45
gmds Avatar answered Dec 02 '25 17:12

gmds