For example if i have:
list1 = [1, 2, 3]
list2 = [4, 5, 6, 7, 8, 9, 10, 11, 12]
How to add elements from list1 to list2 in a loop until list2 is over, where output becomes:
list3 = [1, 4, 2, 5, 3, 6, 1, 7, 2, 8, 3, 9, 1, 10, 2, 11, 3, 12]
For example if i have:
list1 = [1, 2, 3]
list2 = [4, 5, 6, 7, 8, 9, 10, 11, 12]
How to add elements from list1 to list2 in a loop until list2 is over, where output becomes:
list3 = [1, 4, 2, 5, 3, 6, 1, 7, 2, 8, 3, 9, 1, 10, 2, 11, 3, 12]
You can use itertools.cycle
to cycle through the first list and zip
the 2 lists together:
>>> from itertools import cycle
>>> [i for pair in zip(cycle(list1), list2) for i in pair]
[1, 4, 2, 5, 3, 6, 1, 7, 2, 8, 3, 9, 1, 10, 2, 11, 3, 12]
If you want to know what's going on, you can check the intermediate result:
>>> list(zip(cycle(list1), list2))
[(1, 4), (2, 5), (3, 6), (1, 7), (2, 8), (3, 9), (1, 10), (2, 11), (3, 12)]
You can remove the list comprehension and do the same thing with just builtin functions:
>>> from itertools import cycle, chain
>>> list(chain(*zip(cycle(list1), list2)))
[1, 4, 2, 5, 3, 6, 1, 7, 2, 8, 3, 9, 1, 10, 2, 11, 3, 12]
If you really want to do it in the long way:
>>> list3 = []
>>> for pair in zip(cycle(list1), list2):
... print(f'{pair=}') # just for understanding what's going on
... for i in pair:
... list3.append(i)
...
pair=(1, 4)
pair=(2, 5)
pair=(3, 6)
pair=(1, 7)
pair=(2, 8)
pair=(3, 9)
pair=(1, 10)
pair=(2, 11)
pair=(3, 12)
>>> list3
[1, 4, 2, 5, 3, 6, 1, 7, 2, 8, 3, 9, 1, 10, 2, 11, 3, 12]
You can interleave the two arrays by doing the following:
import numpy as np
list1_tiled = np.tile([1, 2, 3], 3)
list2 = np.array([4, 5, 6, 7, 8, 9, 10, 11, 12])
np.ravel(np.column_stack((list1_tiled, list2)))
Output:
array([ 1, 4, 2, 5, 3, 6, 1, 7, 2, 8, 3, 9, 1, 10, 2, 11, 3, 12])
If you want a really simple, no import solution, you can just continuously rotate out the first element in your first list
.
list1 = [1, 2, 3]
list2 = [4 ,5 ,6, 7, 8, 9, 10, 11, 12]
list3 = []
for i in list2:
list3.extend([list1[0], i])
# this pops the first element from your list
# and appends it to the end.
list1.append(list1.pop(0))
print(list3)
This essentially makes list1
an infinitely rotating list
, sort of like collections.deque
.