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.
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)
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]
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