I am trying to make a program where I have a list my_list_1 = [1,2,3,...]
and a second list `my_list_2 = [1,2,3,...] and len(my_list_1) < len(my_list_2). I want to iterate through the lists like this:
my_list_1 = [1,2,3]
my_list_2 = [5,6,7,8,9]
result = []
for i in range(len(my_list_2)):
result.append(my_list_1[i] my_list_2[i])
# i == 0: 1 5 = 6
# i == 1: 2 6 = 8
# i == 2: 3 7 = 10
# i == 3: 1 8 = 9
# i == 4: 2 9 = 11
""" what I want to happen is when i > len(my_list_1), instead of giving a index out of range
error, I want the loop to start at the beginning if the smaller list"""
I tried something like this:
for i in range(len(my_list_2)):
if i % (len(my_list_1) - 1) == 0 or i == 0:
x = 0
else:
x =1
result.append(my_list_1[x] my_list_2[i])
or
for i in range(len(my_list_2)):
if x == (len(my_list_1) - 1) or i == 0:
x = 0
else:
x = 1
result.append(my_list_1[x] my_list_2[i])
this works but I am looking for something a bit more elegant and possibibly even making a copy of my_list_1
and extend it to the length of my_list_2
so that it would look like this:
>>> my_list_1 = [1,2,3]
>>> my_list_2 = [5,6,7,8,9]
>>> extend_list(my_list_1, len(my_list_2))
[1,2,3,1,2]
CodePudding user response:
You can also use itertools.cycle
to create a cyclical list iterator, and use zip
for the iterator and the other list.
from itertools import cycle
my_list_1 = [1,2,3]
my_list_2 = [5,6,7,8,9]
# I use list comprehension here
result = [ a b for a, b in zip(cycle(my_list_1), my_list_2) ]
print(result)
# [6, 8, 10, 9, 11]
CodePudding user response:
You just need modulo for the first index:
for i in range(len(my_list_2)):
x = i % len(my_list_1)
result.append(my_list_1[x] my_list_2[i])